Nestjs define GraphQL Object type got this error: Schema must contain uniquely named types but contains multiple types named "Address"

Nestjs define GraphQL Object type got this error: Schema must contain uniquely named types but contains multiple types named "Address"

我使用 Nestjs 和 GraphQL 进行后端开发,当我定义模型 class(代码优先)时,出现以下错误:架构必须包含唯一命名的类型,但包含多个名为“地址”的类型。以下是我的 Reader 模型文件:

@ObjectType()
class Address {
  @Field()
  homeAddress: string;
  @Field()
  province: string;
  @Field()
  postcode: string;
}

@ObjectType()
class FavouriteBook {
  @Field()
  bookID: string;
  @Field()
  createDate: Date;
}

@ObjectType()
export class ReaderProfile {
  @Field()
  _id: string;
  @Field()
  firstName: string;
  @Field()
  lastName: string;
  @Field()
  gender: string;
  @Field()
  birthday: Date;
  @Field()
  address?: Address;
  @Field()
  postcode: string;
  @Field(type => Int)
  readTimes: number;
  @Field(type => Int)
  readDuration: number;
  @Field(type => Int)
  score: number;
  @Field()
  securityQuestion: string;
  @Field()
  securityAnswer: string;
}

@ObjectType()
export class ReaderReadHistory {
  @Field()
  _id: string;
  @Field()
  bookID: string;
  @Field(type => Int)
  currentPage: number;
  @Field()
  startTime: Date;
  @Field()
  lastReadTime: Date;
  @Field(type => Int)
  readTimes: number;
  @Field(type => Int)
  readDuration: number;
}

@ObjectType()
export class Reader {
  @Field()
  _id: string;
  @Field()
  username: string;
  @Field()
  password: string;
  @Field()
  email: string;
  @Field()
  registerDate: Date;
  @Field()
  isActive: boolean;
  @Field({ nullable: true })
  currentRefreshToken?: string;
  @Field(type => ReaderProfile)
  readerProfile: ReaderProfile;
  @Field(type => [FavouriteBook])
  favouriteBook: FavouriteBook[];
  @Field(type => [ReaderReadHistory])
  readHistory: ReaderReadHistory[];
}

这是我在应用模块中的 GraghQL 配置:(代码优先)

GraphQLModule.forRoot({
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      cors: false,
      sortSchema: true,
      context: ({ req }) => ({ req }),
    }),

有谁知道如何解决这个问题?非常感谢!

最后没找到原因,改成schema first coding,效果不错。希望这对那些有同样问题但不能用代码优先方法解决的人有所帮助,请先尝试模式。另外我发现模式优先的方法有更少的沸腾板,特别是你可以使用单独的自动生成功能(参考下文)在一个文件中生成所有类型脚本接口,这很有帮助。

import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
import { join } from 'path';

const definitionsFactory = new GraphQLDefinitionsFactory();
definitionsFactory.generate({
  typePaths: ['./src/**/*.graphql'],
  path: join(process.cwd(), 'src/graphql.ts'),
});