Brian Nguyen
Posted on December 4, 2023
Quick demo video: https://youtu.be/9KKrkOEhd-I
Install nest-cli if needed
npm i -g @nestjs/cli
Create new nest project
nest new nest-graphql-example
Add first resolver
@Resolver()
class UserResolver {
@Query(() => GraphQLString)
hello() {
return 'World!';
}
}
Start server
yarn start:dev
or
npm run start:dev
First query
{
hello
}
User Object Type
@ObjectType()
class User {
@Field()
id: string;
@Field()
password: string;
@Field()
name: string;
@Field()
email: string;
}
CreateUserInput
@InputType()
class CreateUserInput {
@Field()
password: string;
@Field()
name: string;
@Field()
email: string;
}
UpdateUserInput
@InputType()
class UpdateUserInput {
@Field()
id: string;
@Field({ nullable: true })
password: string;
@Field({ nullable: true })
name: string;
@Field({ nullable: true })
email: string;
}
UserService
@Injectable()
class UserService {
private users: User[] = [];
public createUser(input: CreateUserInput) {
const user = {
id: Date.now().toString(),
...input,
};
this.users.push(user);
return user;
}
public updateUser(input: UpdateUserInput) {
const user = this.users.find((user) => user.id === input.id);
if (!user) {
throw new NotFoundException('User not found');
}
if (user) {
Object.assign(user, input);
}
return user;
}
public getUser(id: string) {
const user = this.users.find((user) => user.id === id);
if (!user) {
throw new NotFoundException('User not found');
}
return user;
}
public getUsers() {
return this.users;
}
}
Final UserResolver
@Resolver()
class UserResolver {
constructor(private readonly userService: UserService) {}
@Query(() => User)
user(@Args('id') id: string) {
return this.userService.getUser(id);
}
@Mutation(() => User)
createUser(@Args('input') input: CreateUserInput) {
return this.userService.createUser(input);
}
@Mutation(() => User)
updateUser(@Args('input') input: UpdateUserInput) {
return this.userService.updateUser(input);
}
@Query(() => [User])
users() {
return this.userService.getUsers();
}
}
Final AppModule
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
playground: true,
autoSchemaFile: true,
}),
],
controllers: [],
providers: [UserResolver, UserService],
})
export class AppModule {}
Final code:
https://gist.github.com/vanpho93/a2649b7a0deb63c35675362de0999b3b
💖 💪 🙅 🚩
Brian Nguyen
Posted on December 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.