I use Nestjs & GraphQL for backend development, when I define model class (code first), I got following error: Schema must contain uniquely named types but contains multiple types named "Address". Following is my Reader model file:
@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[];
}
And this is my GraghQL configuration in app module: (code first)
GraphQLModule.forRoot({
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
cors: false,
sortSchema: true,
context: ({ req }) => ({ req }),
}),
Does anyone know how to fix this? Thanks a lot!
Eventually I did not find reason, and I changed coding to schema first which works well as expected. Hopefully this help for those have same issue but can't fixed with code first approach, try schema first. Also I found schema first approach has less boil-plates, especially you can use separate auto generate function (refer to following) to generate all the type script interfaces in one file, there is pretty helpful.
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'),
});