0
0
NestjsHow-ToBeginner ยท 4 min read

How to Use GraphQL with NestJS: Simple Guide

To use GraphQL with NestJS, install the @nestjs/graphql package and configure the GraphQLModule in your app module. Define your schema using decorators like @ObjectType() and @Resolver(), then create resolver methods to handle queries and mutations.
๐Ÿ“

Syntax

In NestJS, you use the GraphQLModule to set up GraphQL. You define your schema using TypeScript classes with decorators like @ObjectType() for types and @Resolver() for query/mutation handlers. Resolver methods use decorators like @Query() and @Mutation() to map GraphQL operations.

  • GraphQLModule.forRoot(): Configures GraphQL in your app.
  • @ObjectType(): Marks a class as a GraphQL type.
  • @Field(): Marks a class property as a GraphQL field.
  • @Resolver(): Defines a resolver class for queries or mutations.
  • @Query() and @Mutation(): Define GraphQL query and mutation methods.
typescript
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { Resolver, Query, Mutation, Args, ObjectType, Field } from '@nestjs/graphql';

@ObjectType()
class Sample {
  @Field()
  message: string;
}

@Resolver(() => Sample)
class SampleResolver {
  @Query(() => Sample)
  getSample() {
    return { message: 'Hello from GraphQL with NestJS!' };
  }

  @Mutation(() => Sample)
  updateSample(@Args('newMessage') newMessage: string) {
    return { message: newMessage };
  }
}

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
    }),
  ],
  providers: [SampleResolver],
})
export class AppModule {}
๐Ÿ’ป

Example

This example shows a simple NestJS app with GraphQL that defines a Sample type and resolver. It supports a query getSample returning a message and a mutation updateSample to change the message.

typescript
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { Resolver, Query, Mutation, Args, ObjectType, Field } from '@nestjs/graphql';
import { NestFactory } from '@nestjs/core';

@ObjectType()
class Sample {
  @Field()
  message: string;
}

@Resolver(() => Sample)
class SampleResolver {
  private currentMessage = 'Hello from GraphQL with NestJS!';

  @Query(() => Sample)
  getSample() {
    return { message: this.currentMessage };
  }

  @Mutation(() => Sample)
  updateSample(@Args('newMessage') newMessage: string) {
    this.currentMessage = newMessage;
    return { message: this.currentMessage };
  }
}

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
      playground: true
    }),
  ],
  providers: [SampleResolver],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log('Server running on http://localhost:3000/graphql');
}

bootstrap();
Output
Server running on http://localhost:3000/graphql
โš ๏ธ

Common Pitfalls

Common mistakes when using GraphQL with NestJS include:

  • Not enabling autoSchemaFile or providing a schema file path in GraphQLModule.forRoot(), which prevents schema generation.
  • Forgetting to add resolver classes to the providers array in the module.
  • Using incorrect return types or missing @Field() decorators on class properties, causing schema errors.
  • Not using @Args() properly to receive arguments in resolver methods.

Example of a common mistake and fix:

typescript
/* Wrong: Missing @Field decorator causes schema error */
@ObjectType()
class WrongSample {
  message: string; // Missing @Field()
}

/* Right: Add @Field decorator */
@ObjectType()
class CorrectSample {
  @Field()
  message: string;
}
๐Ÿ“Š

Quick Reference

Here is a quick reference for key decorators and setup steps:

ConceptDescription
GraphQLModule.forRoot()Configures GraphQL in NestJS app with options like schema generation and playground.
@ObjectType()Marks a class as a GraphQL type to define schema objects.
@Field()Marks a class property as a GraphQL field.
@Resolver()Defines a resolver class for queries and mutations.
@Query()Defines a GraphQL query method.
@Mutation()Defines a GraphQL mutation method.
@Args()Extracts arguments passed to queries or mutations.
โœ…

Key Takeaways

Install and configure @nestjs/graphql with GraphQLModule.forRoot() to enable GraphQL in NestJS.
Use @ObjectType and @Field decorators to define GraphQL schema types with TypeScript classes.
Create resolver classes with @Resolver and define query/mutation methods using @Query and @Mutation.
Always add resolver classes to the module's providers array to register them.
Enable autoSchemaFile option to generate schema automatically and avoid schema errors.