carsten
carsten

Reputation: 301

Schema Generator cannot determine GraphQL output type for custom object within DTO

Coming from a laravel background I try to get into node.js/graphQL/MongoDB and stumbled over nest.js framework which looks pretty nice. So I tried to set up a simple GraphQL API for testing and understanding how it all works. Therefore I created a mongoose Schema for a user as well as a model (type-graphql) and a DTO for creating such a user via mutation.

This works pretty fine but then I wanted to add a nested object called settings within the user to try how this would work and I simply don't get it and also don't find any nest.js or type-graphql specific examples for such an implementation. Is this simply not feasible using the "code first" approach of nest.js? Because the schema generator always gives me an error while compilation saying :

"UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for settings".

user.model.ts

import { Field, ID, ObjectType } from 'type-graphql'
import UserSettingsType from './user.settings.type'

@ObjectType()
export class User {
  @Field((type) => ID)
  id: string

  @Field()
  email: string

  @Field((type) => UserSettingsType)
  settings: {}
}

user.settings.type.ts

import { Field, ObjectType } from 'type-graphql'

@ObjectType()
export class UserSettings {
  @Field()
  theme: string

  @Field()
  description?: string

  @Field((type) => [String])
  visited: string[]
}

new-user.input.ts

import { IsOptional, IsEmail, IsBoolean, Length, MaxLength, IsArray } from 'class-validator'
import { Field, InputType } from 'type-graphql'
import UserSettingsType from '../graphql/user.settings.type'

@InputType()
export class NewUserInput {
  @Field()
  @IsEmail()
  email: string

  @Field((type) => UserSettingsType)
  @IsOptional()
  @IsArray()
  settings: {}
}

As you can see I defined a new type UserSettings in a separate file (following the best practices of nest.js) and allocated it as a type within the User model as well as the new-user DTO class. The error is thrown for the DTO class (NOT for the model) and if I change it there to something like [String] instead of UserSettingsType it is compiling.

I'm not sure if you need the resolver or the service/mongoose logic for this actual problem if so I can also post that of course!

Upvotes: 9

Views: 11986

Answers (1)

T.Chmelevskij
T.Chmelevskij

Reputation: 2139

Had similar issue migrating from express to nestjs.

After reading the docs realised that problem isn't the nested objects, but wrong imports.

You should use @nestjs/graphql imports instead of type-graphql.

E.G.

// changes this
import { Field, ID, ObjectType } from 'type-graphql'
// to
import { Field, ID, ObjectType } from '@nestjs/graphql'

Same applies to any other import from type-graphql

Upvotes: 19

Related Questions