Skip to content

NestJS GraphQL Code-First

In code-first GraphQL, TypeScript classes and decorators are the source of truth and Nest generates the schema file. This lesson shows models, inputs, and schema generation.

Object Types With Decorators

Mark model classes with @ObjectType() and fields with @Field(). Nest uses these metadata declarations (plus resolvers) to emit schema.gql.

@ObjectType()
export class Cat {
  @Field(() => ID)
  id: string;

  @Field()
  name: string;

  @Field({ nullable: true })
  breed?: string;
}

Nullable fields must be marked { nullable: true } or GraphQL will treat them as required.

Enabling Auto Schema File

GraphQLModule.forRoot({
  driver: ApolloDriver,
  autoSchemaFile: true, // or a path like 'src/schema.gql'
})
  • Code-first keeps schema and TypeScript types aligned in one place.
  • Generated schema files can be committed for review or gitignored—pick a team convention.
  • Use @InputType() for mutation inputs and @ArgsType() for query argument groups.
  • Unions, enums, and interfaces have matching Nest GraphQL decorators.

Code-First Cheatsheet

Decorators that drive schema generation.

Decorator Generates
@ObjectType() GraphQL object type
@Field() Object/input field
@InputType() Input object type
@ArgsType() Grouped arguments type
@Directive() Schema directives

Pros and Cons

Pros: single language, strong Nest/TS integration. Cons: schema design can feel secondary, and generated SDL may need review discipline for API contracts.

Sharing Types Across Modules

Keep GraphQL model classes in a shared or feature-owned models/ folder imported by resolvers. Avoid circular imports between resolvers and models.

Common Mistakes

  • Forgetting nullable: true and generating incorrect required fields.
  • Exposing every entity column as a GraphQL field by habit.
  • Not reviewing generated SDL after larger type changes.
  • Mixing code-first models with competing schema-first files without a clear boundary.

Key Takeaways

  • Code-first uses TypeScript decorators to generate GraphQL schema.
  • @ObjectType and @Field define the public GraphQL model.
  • autoSchemaFile writes the SDL Nest generates.
  • Treat generated schema as an API contract worth reviewing.

Pro Tip

Commit the generated schema.gql in PRs for APIs consumed by other teams—diffs make accidental breaking changes visible.