How to create GraphQL API in Nest JS? Step by Step guidelines!

How to create GraphQL API in Nest JS? Step by Step guidelines!


Creating a GraphQL API in NestJS involves several steps. Here’s a step-by-step theoretical guide:



Step 1: Setup a New NestJS Project

  1. Install Nest CLI:
   npm install -g @nestjs/cli
Enter fullscreen mode

Exit fullscreen mode

  1. Create a New Project:
   nest new project-name
Enter fullscreen mode

Exit fullscreen mode

  1. Navigate to the Project Directory:
   cd project-name
Enter fullscreen mode

Exit fullscreen mode



Step 2: Install GraphQL and Apollo Server

  1. Install Required Packages:
   npm install @nestjs/graphql graphql apollo-server-express
Enter fullscreen mode

Exit fullscreen mode



Step 3: Configure GraphQL Module

  1. Create a GraphQL Module Configuration:
    Open src/app.module.ts and configure the GraphQL module:
   import { Module } from '@nestjs/common';
   import { GraphQLModule } from '@nestjs/graphql';
   import { join } from 'path';

   @Module({
     imports: [
       GraphQLModule.forRoot({
         autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
       }),
     ],
   })
   export class AppModule {}
Enter fullscreen mode

Exit fullscreen mode



Step 4: Create a Resolver

  1. Generate a Resolver:
    Use the Nest CLI to generate a resolver:
   nest g resolver user
Enter fullscreen mode

Exit fullscreen mode

  1. Define Resolver Logic:
    Open src/user/user.resolver.ts and define the resolver logic:
   import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
   import { UserService } from './user.service';
   import { User } from './user.entity';
   import { CreateUserInput } from './dto/create-user.input';

   @Resolver(of => User)
   export class UserResolver {
     constructor(private readonly userService: UserService) {}

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

     @Mutation(returns => User)
     async createUser(@Args('createUserInput') createUserInput: CreateUserInput) {
       return this.userService.create(createUserInput);
     }
   }
Enter fullscreen mode

Exit fullscreen mode



Step 5: Create a Service

  1. Generate a Service:
    Use the Nest CLI to generate a service:
   nest g service user
Enter fullscreen mode

Exit fullscreen mode

  1. Implement Service Logic:
    Open src/user/user.service.ts and implement the service logic:
   import { Injectable } from '@nestjs/common';
   import { User } from './user.entity';
   import { CreateUserInput } from './dto/create-user.input';

   @Injectable()
   export class UserService {
     private users: User[] = [];

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

     create(createUserInput: CreateUserInput): User {
       const user = { ...createUserInput, id: Date.now().toString() };
       this.users.push(user);
       return user;
     }
   }
Enter fullscreen mode

Exit fullscreen mode



Step 6: Define GraphQL Schema and DTOs

  1. Create GraphQL Schema and DTOs:
    Create the src/user/user.entity.ts:
   import { ObjectType, Field, ID } from '@nestjs/graphql';

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

     @Field()
     name: string;

     @Field()
     email: string;
   }
Enter fullscreen mode

Exit fullscreen mode

Create the src/user/dto/create-user.input.ts:

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

   @InputType()
   export class CreateUserInput {
     @Field()
     name: string;

     @Field()
     email: string;
   }
Enter fullscreen mode

Exit fullscreen mode



Step 7: Update Module

  1. Update the Module to include Resolver and Service:
    Open src/user/user.module.ts and update it:
   import { Module } from '@nestjs/common';
   import { UserService } from './user.service';
   import { UserResolver } from './user.resolver';

   @Module({
     providers: [UserService, UserResolver],
   })
   export class UserModule {}
Enter fullscreen mode

Exit fullscreen mode



Step 8: Integrate the User Module

  1. Integrate the User Module into the App Module:
    Open src/app.module.ts and update it:
   import { Module } from '@nestjs/common';
   import { GraphQLModule } from '@nestjs/graphql';
   import { join } from 'path';
   import { UserModule } from './user/user.module';

   @Module({
     imports: [
       GraphQLModule.forRoot({
         autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
       }),
       UserModule,
     ],
   })
   export class AppModule {}
Enter fullscreen mode

Exit fullscreen mode



Step 9: Run the Application

  1. Start the NestJS Application:
   npm run start:dev
Enter fullscreen mode

Exit fullscreen mode



Step 10: Test the GraphQL API

  1. Access the GraphQL Playground:
    Navigate to http://localhost:3000/graphql to access the GraphQL playground and test your API by running queries and mutations.

This guide provides a foundational approach to creating a GraphQL API in NestJS. You can further expand and customize it based on your application’s requirements.

Disclaimer: This content in generated by AI.



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.