Tiếp tục với series, sau Bài 23 TaskFlow đã có REST API kèm tài liệu. Bài này mình sẽ giới thiệu với mọi người về GraphQL trong NestJS, một cách khác để client đọc và sửa dữ liệu.
1. GraphQL là gì? So sánh với REST.
GraphQL là ngôn ngữ truy vấn cho API. Server mô tả dữ liệu bằng một schema có kiểu, client gửi truy vấn tới một endpoint duy nhất (POST /graphql) và chọn đúng các field cần lấy. Truy vấn đọc là query, ghi là mutation.
Khác với REST (nhiều URL, server quyết định response, dễ cache theo URL), GraphQL không trả thừa hay thiếu field, schema tự mô tả (introspection), lỗi nằm trong mảng errors. TaskFlow giữ REST và thêm GraphQL bên cạnh.
2. Cài đặt GraphQLModule.
@nestjs/graphql (14.2.1) có hai driver: Apollo (@nestjs/apollo) và Mercurius (chỉ chạy với Fastify). TaskFlow dùng Express nên chọn Apollo Server 5:
npm install @nestjs/graphql @nestjs/apollo @apollo/server @as-integrations/express5 graphql
- src/app.module.ts (đoạn trích trong imports; import thêm GraphQLModule, ApolloDriver, ApolloDriverConfig, join, Request, Response)
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
inject: [appConfig.KEY],
useFactory: (app: ConfigType<typeof appConfig>) => ({
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
sortSchema: true,
// Production: tắt GraphiQL và introspection như /docs
graphiql: app.docsEnabled,
introspection: app.docsEnabled,
// Guard, decorator đọc req (và res) từ context
context: ({ req, res }: { req: Request; res: Response }) => ({
req,
res,
}),
}),
}),
Trong đó:
- Code first: NestJS sinh schema từ class và ghi ra
src/schema.gql(cách còn lại là schema first: tự viết file.graphql). - GraphiQL là trang thử truy vấn ở
/graphql, mặc định bật khiNODE_ENVkhácproduction; mình ghi rõ cùng điều kiện với/docs(Bài 23). Tắt introspection chưa đủ: gõ sai tên field, gợi ýDid you mean "project"?vẫn lộ schema ở production, Bài 25 sẽ ẩn nó.
3. ObjectType và Field.
Kiểu dữ liệu trả về là class gắn @ObjectType(), mỗi field gắn @Field():
- src/projects/models/project.model.ts (đoạn trích, description, ownerId, createdAt, updatedAt tương tự)
import { Field, Int, ObjectType } from '@nestjs/graphql';
// Kiểu Project trong schema (khác type Project của Prisma)
@ObjectType('Project')
export class ProjectModel {
@Field(() => Int)
id: number;
@Field()
name: string;
}
number mặc định là Float nên ghi () => Int, Date thành scalar DateTime, field có thể null thêm { nullable: true }. Field không khai báo thì client không lấy được. TaskModel làm tương tự, enum của Prisma đăng ký bằng registerEnumType(TaskStatus, { name: 'TaskStatus' }) rồi dùng @Field(() => TaskStatus).
4. Resolver với Query và Mutation.
Resolver giống controller của REST, tạo bằng Nest CLI:
nest g resolver projects --no-spec --format
nest g resolver tasks --no-spec --format
- src/projects/projects.resolver.ts (đoạn trích; Args, Int, Mutation, Query, Resolver từ @nestjs/graphql)
@Resolver(() => ProjectModel)
export class ProjectsResolver {
constructor(private readonly projectsService: ProjectsService) {}
@Query(() => [ProjectModel])
async projects(
@Args() query: ListProjectsQueryDto,
@CurrentUser() user: AuthUser,
): Promise<Project[]> {
const result = await this.projectsService.findAll(query, user.id);
return result.data;
}
@Mutation(() => ProjectModel)
updateProject(
@Args('id', { type: () => Int }) id: number,
@Args('input') input: UpdateProjectInput,
@CurrentUser() user: AuthUser,
): Promise<Project> {
return this.projectsService.update(id, input, user.id);
}
@Query() / @Mutation() thêm field (tên method) vào kiểu gốc Query / Mutation. @Args('id', ...) lấy một tham số, @Args() lấy cả class tham số. Service nhận user.id như ở controller nên project của người khác vẫn "không tìm thấy" (Bài 21).
Ngoài ra còn project(id), createProject, removeProject (trả Boolean); TasksResolver có task(id), createTask, updateTask, removeTask.
5. InputType, ArgsType và validation.
Tham số kiểu object của mutation là input type. Mình gắn decorator GraphQL vào DTO sẵn có (Bài 7), validation chỉ viết một lần:
- src/projects/dto/create-project.dto.ts (đoạn trích, thêm import { Field, InputType } from '@nestjs/graphql';)
// Dùng chung: body của REST và input của GraphQL
@InputType('CreateProjectInput')
export class CreateProjectDto {
@Field()
@IsString()
@IsNotEmpty()
@MaxLength(100)
name: string;
description thêm @Field({ nullable: true }). Input để sửa dùng PartialType của @nestjs/graphql (bản của Swagger không chép @Field):
- src/projects/dto/update-project.input.ts
import { InputType, PartialType } from '@nestjs/graphql';
import { CreateProjectDto } from './create-project.dto.js';
@InputType('UpdateProjectInput')
export class UpdateProjectInput extends PartialType(CreateProjectDto, {
skipNullProperties: false, // null vẫn bị validate như REST
}) {}
PaginationQueryDto, ListProjectsQueryDto (Bài 18) gắn @ArgsType() và @Field() cho từng property (mặc định lấy từ initializer), CreateTaskDto gắn @InputType('CreateTaskInput'). ValidationPipe toàn cục vẫn kiểm tra, nên limit: 1000 bị chặn.
6. Guard, interceptor và filter với GraphQL.
Guard, interceptor, filter toàn cục cũng chạy cho resolver, nhưng tham số là (root, args, context, info) nên switchToHttp() không dùng được. Mình viết hàm dùng chung:
- src/common/utils/get-req-res.ts
import type { ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext, type GqlContextType } from '@nestjs/graphql';
import type { Response } from 'express';
import type { AuthRequest } from '../../auth/auth-user.js';
// Lấy request/response của Express cho cả route REST lẫn resolver GraphQL
export function getReqRes(context: ExecutionContext): {
req: AuthRequest;
res: Response;
} {
if (context.getType<GqlContextType>() === 'graphql') {
return GqlExecutionContext.create(context).getContext();
}
const http = context.switchToHttp();
return { req: http.getRequest(), res: http.getResponse() };
}
JwtAuthGuard,RolesGuard,@CurrentUser()đổiswitchToHttp().getRequest()thànhgetReqRes(context).req.AppModulethayThrottlerGuardbằngAppThrottlerGuard(src/common/guards/app-throttler.guard.ts), class con ghi đègetRequestResponse(context)trả vềgetReqRes(context).TransformInterceptor(Bài 13) không bọc{ data }khicontext.getType() === 'graphql'.PrismaExceptionFilterđổi thànhreturn super.catch(...), cònAllExceptionsFiltertrả exception về cho Apollo:
- src/common/filters/all-exceptions.filter.ts (đoạn trích đầu catch(); import thêm InternalServerErrorException, GqlContextType; kiểu trả về đổi thành HttpException | void; console.error chuyển từ nhánh else lên đầu để lỗi GraphQL cũng được in ra)
if (!(exception instanceof HttpException)) {
// Lỗi ngoài dự kiến: in ra console để sửa, không gửi chi tiết cho client
console.error(exception);
}
if (host.getType<GqlContextType>() === 'graphql') {
// GraphQL không dùng response của Express: trả exception để Apollo đưa vào "errors"
return exception instanceof HttpException
? exception
: new InternalServerErrorException();
}
7. Thử với GraphiQL và curl.
Chạy npm run start, mở http://localhost:3000/graphql, thêm {"Authorization": "Bearer <token>"} ở tab Headers. Với curl, reset dữ liệu như Bài 22, $A là token của tai, $B của An (Bài 21):
G=http://localhost:3000/graphql
curl $G -H "$A" -H "Content-Type: application/json" -d '{"query":"{ projects { id name } }"}'
# {"data":{"projects":[{"id":1,"name":"Website toidicode.com"},{"id":2,"name":"TaskFlow API"}]}}
curl $G -H "$A" -H "Content-Type: application/json" -d '{
"query": "mutation ($input: CreateTaskInput!) { createTask(input: $input) { id title status } }",
"variables": { "input": { "projectId": 2, "title": "Viết resolver" } }
}'
# {"data":{"createTask":{"id":1,"title":"Viết resolver","status":"todo"}}}
curl $G -H "$B" -H "Content-Type: application/json" -d '{"query":"{ project(id: 1) { id } }"}'
# {"errors":[{"message":"Không tìm thấy project 1",...,"extensions":{"code":"INTERNAL_SERVER_ERROR",...,"status":404,...}}],"data":null}
Lỗi 400, 401, 403 có mã BAD_REQUEST, UNAUTHENTICATED, FORBIDDEN, mã khác (VD 404) thành INTERNAL_SERVER_ERROR kèm status; chi tiết (VD lỗi validation) nằm ở extensions.originalError. Phần lược ... có stacktrace, production thì không.
Lưu ý: Khi các kiểu có quan hệ, truy vấn có thể lồng rất sâu, nên giới hạn độ phức tạp (VD graphql-query-complexity).
8. Lời kết.
Như vậy mình đã giới thiệu với mọi người phần 1 về GraphQL trong NestJS: code first với @ObjectType, resolver, query, mutation, DTO làm input và cho guard, filter chạy với GraphQL. Bài sau mình sẽ giới thiệu tiếp về quan hệ với @ResolveField, DataLoader chống N+1 và subscription.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments