Creating a GraphQL API in NestJS involves several steps. Here's a step-by-step theoretical guide:
Step 1: Setup a New NestJS Project
- Install Nest CLI:
npm install -g @nestjs/cli
- Create a New Project:
nest new project-name
- Navigate to the Project Directory:
cd project-name
Step 2: Install GraphQL and Apollo Server
- Install Required Packages:
npm install @nestjs/graphql graphql apollo-server-express
Step 3: Configure GraphQL Module
-
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 {}
Step 4: Create a Resolver
- Generate a Resolver: Use the Nest CLI to generate a resolver:
nest g resolver user
-
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);
}
}
Step 5: Create a Service
- Generate a Service: Use the Nest CLI to generate a service:
nest g service user
-
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;
}
}
Step 6: Define GraphQL Schema and DTOs
-
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;
}
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;
}
Step 7: Update Module
-
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 {}
Step 8: Integrate the User Module
-
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 {}
Step 9: Run the Application
- Start the NestJS Application:
npm run start:dev
Step 10: Test the GraphQL API
-
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.
If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!
Disclaimer: This content is generated by AI.
Top comments (0)