首页 > 解决方案 > Getting error with GraphQL model in NestJS, using code-first approach

问题描述

I'm using the code-first approach in NestJS to create GraphQL schemas. I have the following definition. Person can have a Dog.

@ObjectType()
export class Person {
  @Field()
  name: string;
  @Field(type => Dog, { nullable: true })
  dog?: Dog;
}

@ObjectType()
export class Dog {
  @Field()
  breed: string
  @Field()
  name: string
}

When server starts up I get the following error message.

ReferenceError: Cannot access 'Dog' before initialization

What am I doing wrong? Does Dog need to be resolved by @ResolveField() in the resolver? In my case it's just a nested object within Person. Dog doesn't come from another service call.

Essentially, I want to represent the following structure.

interface Person {
  name: string;
  dog?: {
    breed: string;
    name: string
  }
}

标签: graphqlnestjs

解决方案


我认为您需要做的就是Dog先声明:

@ObjectType()
export class Dog {
  @Field()
  breed: string;
  @Field()
  name: string;
}

@ObjectType()
export class Person {
  @Field()
  name: string;
  @Field(type => Dog, { nullable: true })
  dog?: Dog;
}

推荐阅读