Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 25: GraphQL trong NestJS (Phần 2)

Tiếp tục với series, ở Bài 24 các kiểu Project, Task vẫn đứng riêng lẻ. Bài này mình sẽ giới thiệu tiếp với mọi người phần 2 về GraphQL trong NestJS.

1. ResolveField và quan hệ.

Field resolver là method tính giá trị cho một field của kiểu cha, chỉ chạy khi client chọn field đó. VD field tasks của Project:

- src/projects/projects.resolver.ts (đoạn trích; Context, Parent, ResolveField từ @nestjs/graphql)

    @ResolveField(() => [TaskModel])
    tasks(
        @Parent() project: Project,
        @Context('loaders') loaders: Loaders,
    ): Promise<TaskWithTags[]> {
        // Project cha đã được lọc theo ownerId nên không cần kiểm tra lại
        return loaders.tasksByProject.load(project.id);
    }

@Resolver(() => ProjectModel) cho biết kiểu cha, @Parent() là object cha. Tương tự, TasksResolver có field project gọi loaders.projectById.load(task.projectId). Task luôn được lấy kèm tags nên TaskModel chỉ thêm @Field(() => [TagModel]) tags: TagModel[] (import từ ./tag.model.js), với kiểu Tag mới:

- src/tasks/models/tag.model.ts

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

@ObjectType('Tag')
export class TagModel {
    @Field(() => Int)
    id: number;

    @Field()
    name: string;
}

Chú ý: Mặc định guard, interceptor, filter không chạy cho @ResolveField (trừ khi bật fieldResolverEnhancers). Quyền đến từ object cha: field resolver chỉ đọc dữ liệu của cha, không nhận id từ client.

2. DataLoader chống N+1.

Với { projects { tasks { id } } }, 10 project là 10 query lấy task, đúng lỗi N+1 ở Bài 17. DataLoader gom các load(key) trong cùng một lượt thành một lần gọi hàm batch:

npm install dataloader

- src/common/graphql/loaders.ts (đoạn trích; import DataLoader from 'dataloader', TaskWithTags = Task & { tags: Tag[] }; projectById viết tương tự)

// Tạo mới cho từng request: dữ liệu cache không lẫn giữa các user
export function createLoaders(prisma: PrismaService, cache = true) {
    return {
        // Mọi projectId cần trong cùng một lượt được gom thành 1 query
        tasksByProject: new DataLoader<number, TaskWithTags[]>(
            async (projectIds) => {
                const tasks = await prisma.task.findMany({
                    where: { projectId: { in: [...projectIds] } },
                    include: { tags: true },
                    orderBy: { id: 'asc' },
                });
                // Kết quả phải cùng thứ tự với danh sách key
                return projectIds.map((id) =>
                    tasks.filter((task) => task.projectId === id),
                );
            },
            { cache },
        ),

Mỗi request nhận bộ loader mới qua context (phần 4). Giờ dù bao nhiêu project thì tasks cũng chỉ tốn một query. Reset dữ liệu như Bài 22, tạo task 1 (project 1, tag ui), task 2, 3 (project 2) bằng createTask rồi thử:

curl $G -H "$A" -H "Content-Type: application/json" -d '{"query":"{ projects { id name tasks { id title tags { name } } } }"}'
# {"data":{"projects":[{"id":1,"name":"Website toidicode.com","tasks":[{"id":1,"title":"Thiết kế giao diện","tags":[{"name":"ui"}]}]},{"id":2,"name":"TaskFlow API","tasks":[{"id":2,...},{"id":3,...}]}]}}

3. Giới hạn độ sâu truy vấn.

Có quan hệ hai chiều thì client gửi được projects { tasks { project { tasks { ... } } } } lồng mãi. Mình dùng validation rule maxDepthRule của @escape.tech/graphql-armor-max-depth (2.4.2):

npm install @escape.tech/graphql-armor-max-depth

- src/app.module.ts (đoạn trích trong useFactory của GraphQLModule)

                // Chặn truy vấn lồng quá 5 cấp, áp dụng cho cả HTTP và WebSocket
                validationRules: [
                    maxDepthRule({
                        n: 5,
                        // Báo lỗi validation (400) thay vì ném lỗi 500
                        propagateOnRejection: false,
                        onReject: [(ctx, error) => ctx?.reportError(error)],
                    }),
                ],
curl $G -H "$A" -H "Content-Type: application/json" -d '{"query":"{ projects { tasks { project { tasks { project { name } } } } } }"}'
# {"errors":[{"message":"Syntax Error: Query depth limit of 5 exceeded, found 6.","extensions":{"code":"GRAPHQL_VALIDATION_FAILED",...}}]}

Độ sâu không giới hạn được độ rộng: một query 3 cấp với hàng trăm alias (a1: projects { ... } a2: projects { ... }) vẫn qua. Muốn chặn thêm thì dùng các validation rule cùng họ @escape.tech/graphql-armor-max-aliases, -cost-limit (cũng chạy qua WebSocket). Tài liệu NestJS dùng plugin graphql-query-complexity, nhưng plugin Apollo không chạy qua WebSocket. Ngoài ra docsEnabled đổi thành NODE_ENV === 'development' (/docs, GraphiQL, introspection chỉ bật ở development) và thêm hideSchemaDetailsFromClientErrors: !app.docsEnabled để lỗi ở production không gợi ý tên field.

4. Subscription với graphql-ws.

Subscription: client mở WebSocket và nhận dữ liệu mỗi khi có sự kiện. @nestjs/graphql 14 chỉ hỗ trợ giao thức graphql-ws (đã bỏ subscriptions-transport-ws):

npm install graphql-ws graphql-subscriptions

WebSocket không có header Authorization như HTTP: client gửi token trong connectionParams lúc kết nối. Mình tạo context sao cho JwtAuthGuard, @CurrentUser() (Bài 20) vẫn đọc req.headers.authorization như cũ:

- src/common/graphql/gql-context.ts (đoạn trích; trên đó là interface GqlContext { req; res?; loaders } và ContextArgs { req?; res?; connectionParams? })

export function createGqlContext(prisma: PrismaService) {
    return ({ req, res, connectionParams }: ContextArgs): GqlContext => {
        if (req) {
            return { req, res, loaders: createLoaders(prisma) };
        }
        // WebSocket: lấy token trong connectionParams làm header Authorization
        const token = connectionParams?.authorization;
        const wsReq = {
            headers: {
                authorization: typeof token === 'string' ? token : undefined,
            },
        } as AuthRequest;
        // Subscription sống lâu: tắt cache để mỗi sự kiện đọc dữ liệu mới
        return { req: wsReq, loaders: createLoaders(prisma, false) };
    };
}

Trong GraphQLModule, inject thêm PrismaService, đặt subscriptions: { 'graphql-ws': true } (path /graphql) và context: createGqlContext(prisma).

Sự kiện phát qua PubSub của graphql-subscriptions, khai báo thành provider (thêm vào providers của TasksModule) để service và resolver dùng chung:

- src/tasks/task-pub-sub.ts

import { Injectable } from '@nestjs/common';
import { PubSub } from 'graphql-subscriptions';
import type { TaskWithRelations } from './tasks.service.js';

export type TaskStatusEvent = {
    taskStatusChanged: TaskWithRelations;
    ownerId: number; // chủ project, dùng để lọc người nhận
};

// PubSub lưu trong bộ nhớ: chỉ đúng khi ứng dụng chạy một instance
@Injectable()
export class TaskPubSub extends PubSub<{
    taskStatusChanged: TaskStatusEvent;
}> {}

TasksService inject TaskPubSub, phát sự kiện khi client gửi status (qua REST hay GraphQL đều có):

- src/tasks/tasks.service.ts (đoạn trích trong update(), ngay trước return task;)

        if (dto.status !== undefined) {
            // Chỉ chủ project sửa được task nên userId cũng là ownerId
            void this.pubSub.publish('taskStatusChanged', {
                taskStatusChanged: task,
                ownerId: userId,
            });
        }

- src/tasks/tasks.resolver.ts (đoạn trích; TaskPubSub inject qua constructor, SkipThrottle từ @nestjs/throttler)

    @SkipThrottle() // WebSocket không có response để throttler ghi header
    @Subscription(() => TaskModel, {
        // Chỉ gửi sự kiện thuộc project của chính user đang subscribe
        filter: (payload: TaskStatusEvent, _variables, context: GqlContext) =>
            payload.ownerId === context.req.user?.id,
    })
    taskStatusChanged() {
        return this.pubSub.asyncIterableIterator('taskStatusChanged');
    }

JwtAuthGuard chạy một lần lúc subscribe (token hết hạn sau đó kết nối vẫn giữ), filter chạy cho từng sự kiện nên An không nhận task của tai.

5. Thử subscription.

Mình thử bằng client graphql-ws, file đặt ở thư mục gốc project:

- sub.mjs

import { createClient } from 'graphql-ws';

// Node.js 24 có sẵn WebSocket
const client = createClient({
    url: 'ws://localhost:3000/graphql',
    // Token gửi một lần lúc kết nối
    connectionParams: { authorization: `Bearer ${process.env.TOKEN}` },
});

client.subscribe(
    {
        query: 'subscription { taskStatusChanged { id title status project { name } } }',
    },
    {
        next: (result) => console.log(JSON.stringify(result)),
        error: (error) => console.error(error),
    },
);

Mở hai terminal chạy TOKEN=<token của tai> node sub.mjs và TOKEN=<token của An> node sub.mjs, rồi tai đổi trạng thái task 2:

curl $G -H "$A" -H "Content-Type: application/json" -d '{"query":"mutation { updateTask(id: 2, input: {status: doing}) { id status } }"}'
# {"data":{"updateTask":{"id":2,"status":"doing"}}}

# Terminal của tai:
# {"data":{"taskStatusChanged":{"id":2,"title":"Viết resolver","status":"doing","project":{"name":"TaskFlow API"}}}}
# Terminal của An: không nhận được gì

Chạy node sub.mjs không có token thì nhận lỗi Unauthorized ngay khi subscribe. Thử xong các bạn xoá sub.mjs.

Lưu ý: Chạy nhiều instance thì cần PubSub dùng Redis (VD graphql-redis-subscriptions), Redis có ở Bài 27.

6. Lời kết.

Như vậy mình đã giới thiệu xong phần 2 về GraphQL trong NestJS: @ResolveField, DataLoader, giới hạn độ sâu truy vấn và subscription qua graphql-ws có xác thực. Bài sau mình sẽ giới thiệu về logging và serialization trong NestJS.

Đă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!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha