Beginner's Guide to Using GraphQL with NestJS

Beginner's Guide to Using GraphQL with NestJS

A Comprehensive Guide to Getting Started with GraphQL in NestJS

GraphQL is a powerful query language for APIs that allows clients to request exactly the data they need. NestJS, a progressive Node.js framework, provides excellent support for building GraphQL APIs. In this guide, we'll explore how to get started with GraphQL in NestJS, covering the essential steps from setting up your project to creating resolvers and defining schemas.

Why Choose GraphQL with NestJS?

  1. Efficient Data Fetching: GraphQL allows clients to request only the data they need, reducing over-fetching and under-fetching.

  2. Strongly Typed Schema: The GraphQL schema provides a clear contract for your API, ensuring type safety and better developer experience.

  3. NestJS Integration: NestJS seamlessly integrates with GraphQL, providing decorators, modules, and tools to simplify development.

Setting Up a NestJS Project with GraphQL

Step 1: Install NestJS CLI

First, install the NestJS Command Line Interface (CLI):

npm install -g @nestjs/cli

Step 2: Create a New Project

Create a new NestJS project using the CLI:

nest new my-graphql-api

Navigate into your project directory:

cd my-graphql-api

Step 3: Install GraphQL Dependencies

Install the necessary GraphQL dependencies:

npm install @nestjs/graphql @nestjs/apollo apollo-server-express graphql

Step 4: Configure GraphQL Module

Open the src/app.module.ts file and configure the GraphQL module:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { UsersModule } from './users/users.module';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
    }),
    UsersModule,
  ],
})
export class AppModule {}

Creating Your First Module, Resolver, and Schema

Step 1: Generate a Module

Generate a new module for users:

nest generate module users

Step 2: Generate a Resolver and Service

Generate a resolver and a service for the users module:

nest generate resolver users
nest generate service users

Step 3: Define User Type

Create a GraphQL type for the user entity in src/users/user.type.ts:

import { Field, ObjectType, Int } from '@nestjs/graphql';

@ObjectType()
export class User {
  @Field(type => Int)
  id: number;

  @Field()
  name: string;

  @Field()
  email: string;
}

Step 4: Implement the Users Service

Open the src/users/users.service.ts file and implement the service methods:

import { Injectable } from '@nestjs/common';
import { User } from './user.type';

@Injectable()
export class UsersService {
  private users: User[] = [
    { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
    { id: 2, name: 'Jane Doe', email: 'jane.doe@example.com' },
  ];

  findAll(): User[] {
    return this.users;
  }

  findOne(id: number): User {
    return this.users.find(user => user.id === id);
  }
}

Step 5: Implement the Users Resolver

Open the src/users/users.resolver.ts file and implement the resolver methods:

import { Resolver, Query, Args, Int } from '@nestjs/graphql';
import { UsersService } from './users.service';
import { User } from './user.type';

@Resolver(of => User)
export class UsersResolver {
  constructor(private usersService: UsersService) {}

  @Query(returns => [User])
  users(): User[] {
    return this.usersService.findAll();
  }

  @Query(returns => User)
  user(@Args('id', { type: () => Int }) id: number): User {
    return this.usersService.findOne(id);
  }
}

Step 6: Testing Your GraphQL API

Run the application:

npm run start

By default, the application runs on http://localhost:3000. Navigate to http://localhost:3000/graphql to access the GraphQL Playground, where you can test your API.

Example queries:

  • Fetch all users:

      {
        users {
          id
          name
          email
        }
      }
    
  • Fetch a user by ID:

      {
        user(id: 1) {
          id
          name
          email
        }
      }
    

"GraphQL is a powerful query language that enables clients to request exactly the data they need, making APIs more efficient and flexible."

Conclusion
NestJS provides robust support for building GraphQL APIs, offering a seamless integration that leverages the framework's modular architecture and TypeScript features. This guide covered the basics of setting up a NestJS project with GraphQL, creating modules, resolvers, and defining schemas. With this foundation, you are well-equipped to build efficient and scalable GraphQL APIs using NestJS.