Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 8: Validation trong NestJS

Tiếp tục với series, ở bài trước TaskFlow API đã nhận được body qua DTO nhưng chưa kiểm tra gì: gửi tên rỗng vẫn tạo project, gửi thêm ownerId là đổi được chủ project. Bài này mình sẽ giới thiệu với mọi người về validation trong NestJS để chặn những dữ liệu đó ngay từ đầu.

1. Validation trong NestJS.

Validation là kiểm tra dữ liệu client gửi lên trước khi xử lý. Trong NestJS việc này do pipe đảm nhận: pipe chạy ngay trước route handler, dữ liệu sai thì ném lỗi và handler không được gọi. Pipe sẽ được giới thiệu kỹ ở Bài 9, bài này dùng hai pipe có sẵn:

  • ValidationPipe: luật kiểm tra là decorator của class-validator đặt trên DTO class.
  • StandardSchemaValidationPipe (mới ở NestJS 12): luật kiểm tra là schema của Zod, Valibot, ArkType... hay bất kỳ thư viện nào theo chuẩn Standard Schema.

2. ValidationPipe với class-validator.

Các bạn cài hai package mà ValidationPipe sử dụng:

npm install class-validator class-transformer

Sau đó đăng ký pipe cho toàn bộ ứng dụng trong main.ts (đoạn trích, thêm ValidationPipe vào import từ @nestjs/common; file đầy đủ ở phần 5):

app.useGlobalPipes(new ValidationPipe());

Tiếp theo các bạn thêm luật vào CreateProjectDto:

- src/projects/dto/create-project.dto.ts

import { IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';

export class CreateProjectDto {
    @IsString()
    @IsNotEmpty()
    @MaxLength(100)
    name: string;

    @IsOptional()
    @IsString()
    @MaxLength(500)
    description?: string;
}

Trong đó:

  • @IsString(): giá trị phải là chuỗi.
  • @IsNotEmpty(): không được là '', null hay undefined (không tự cắt khoảng trắng nên " " vẫn qua).
  • @MaxLength(n): chuỗi dài tối đa n ký tự.
  • @IsOptional(): khi field là null/undefined thì bỏ qua các luật còn lại.

Danh sách decorator đầy đủ xem tại đây. Chạy lại ứng dụng và gửi dữ liệu sai:

curl -X POST http://localhost:3000/api/v1/projects \
    -H 'Content-Type: application/json' \
    -d '{"name":"","description":123}'
# {"message":["name should not be empty","description must be shorter than or equal to 500 characters","description must be a string"],"error":"Bad Request","statusCode":400}

Client nhận 400 Bad Request kèm danh sách lỗi. Request không có body giờ cũng nhận 400 (name must be a string...) thay vì lỗi 500 như bài trước.

UpdateProjectDto tạo bằng PartialType() thừa hưởng các luật này, mỗi field được gắn thêm @IsOptional() nên {"name":null} sẽ lọt qua và xoá mất tên project. Truyền thêm skipNullProperties: false để chỉ bỏ qua field không gửi lên, còn null vẫn bị kiểm tra:

- src/projects/dto/update-project.dto.ts

import { PartialType } from '@nestjs/mapped-types';
import { CreateProjectDto } from './create-project.dto.js';

export class UpdateProjectDto extends PartialType(CreateProjectDto, {
    skipNullProperties: false,
}) {}
curl -X PATCH http://localhost:3000/api/v1/projects/2 \
    -H 'Content-Type: application/json' \
    -d '{"name":null}'
# {"message":["name must be shorter than or equal to 100 characters","name should not be empty","name must be a string"],"error":"Bad Request","statusCode":400}

3. Whitelist, forbidNonWhitelisted và transform.

Ba option hay dùng nhất của ValidationPipe:

  • whitelist: true: xoá các field không có decorator nào trong DTO.
  • forbidNonWhitelisted: true (dùng cùng whitelist): thay vì xoá thì trả lỗi 400.
  • transform: true: chuyển body thành instance của DTO class, đồng thời chuyển param/query sang kiểu đã khai báo (VD @Param('id') id: number nhận số thay vì chuỗi).

VD: Với new ValidationPipe({ whitelist: true }), lỗ hổng gán dữ liệu hàng loạt ở bài trước đã bị chặn, ownerId và isAdmin bị bỏ đi trước khi đến service:

curl -X PATCH http://localhost:3000/api/v1/projects/2 \
    -H 'Content-Type: application/json' \
    -d '{"ownerId":99,"isAdmin":true}'
# {"id":2,"name":"TaskFlow API","description":"Học NestJS","ownerId":1}

Thêm forbidNonWhitelisted: true rồi gửi lại, client biết ngay mình gửi sai:

# {"message":["property ownerId should not exist","property isAdmin should not exist"],"error":"Bad Request","statusCode":400}

Với transform: true, createProjectDto instanceof CreateProjectDto trong handler đã là true. TaskFlow API bật cả ba option, riêng việc chuyển kiểu param mình sẽ dùng ParseIntPipe ở Bài 9.

4. Option errorFormat (mới ở NestJS 12).

Mặc định (errorFormat: 'list') message là một mảng chuỗi như các ví dụ trên. NestJS 12 thêm new ValidationPipe({ errorFormat: 'grouped' }), trả về object nhóm lỗi theo tên field, tiện cho frontend hiển thị lỗi dưới từng ô input:

curl -X POST http://localhost:3000/api/v1/projects \
    -H 'Content-Type: application/json' \
    -d '{"name":"","description":123}'
# {"message":{"name":["name should not be empty"],"description":["description must be shorter than or equal to 500 characters","description must be a string"]},"error":"Bad Request","statusCode":400}

Lưu ý: Với 'grouped' message đổi từ mảng sang object, code đang đọc nó như mảng phải sửa lại. TaskFlow API giữ mặc định 'list', định dạng lỗi chung mình sẽ làm ở Bài 10.

5. Standard Schema với Zod và Valibot.

Ở NestJS 12, các decorator @Body(), @Query(), @Param() có thêm option schema. Schema vừa kiểm tra lúc chạy vừa suy ra kiểu TypeScript. Mình sẽ dùng Zod để sửa lỗi 500 khi gửi ?search hai lần ở bài trước:

npm install zod

- src/projects/projects.controller.ts (đoạn trích, các route khác giữ nguyên)

import { z } from 'zod';

// ...

@Get()
findAll(
    @Query('search', { schema: z.string().trim().max(50).optional() })
    search?: string,
): Project[] {
    return this.projectsService.findAll(search);
}

Option schema chỉ gắn metadata, phải đăng ký thêm StandardSchemaValidationPipe thì mới có kiểm tra:

- src/main.ts

import {
    StandardSchemaValidationPipe,
    ValidationPipe,
    VersioningType,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap() {
    const app = await NestFactory.create(AppModule, {
        routeConflictPolicy: { duplicate: 'error' },
        routeResolutionStrategy: 'specificity',
    });
    app.setGlobalPrefix('api');
    app.enableVersioning({
        type: VersioningType.URI,
        defaultVersion: '1',
    });
    app.useGlobalPipes(
        new StandardSchemaValidationPipe(),
        new ValidationPipe({
            whitelist: true,
            forbidNonWhitelisted: true,
            transform: true,
        }),
    );
    await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
curl "http://localhost:3000/api/v1/projects?search=web&search=api"
# {"message":["Invalid input: expected string, received array"],"error":"Bad Request","statusCode":400}

curl "http://localhost:3000/api/v1/projects?search=%20%20api%20"
# [{"id":2,"name":"TaskFlow API","description":"Học NestJS","ownerId":1}]

StandardSchemaValidationPipe bỏ qua tham số không có schema, ValidationPipe chỉ kiểm tra tham số kiểu class, nên hai pipe dùng chung được. Schema còn chuyển đổi giá trị: .trim() cắt khoảng trắng nên " api " vẫn tìm ra project.

Chú ý: Pipe toàn cục chạy theo thứ tự đăng ký. Nếu đặt ValidationPipe (có transform) lên trước, nó sẽ đổi mảng thành chuỗi "web,api" trước khi schema kịp kiểm tra.

Schema cho body.

Body cũng kiểm tra được bằng schema. VD: Phiên bản Zod của CreateProjectDto (minh hoạ, không thêm vào project):

import { z } from 'zod';

export const createProjectSchema = z.strictObject({
    name: z.string().trim().min(1).max(100),
    description: z.string().max(500).optional(),
});

export type CreateProjectInput = z.infer<typeof createProjectSchema>;
@Post()
create(@Body({ schema: createProjectSchema }) input: CreateProjectInput) {
    return this.projectsService.create(input);
}
curl -X POST http://localhost:3000/api/v1/projects \
    -H 'Content-Type: application/json' \
    -d '{"name":"  ","description":123}'
# {"message":["name: Too small: expected string to have >=1 characters","description: Invalid input: expected string, received number"],"error":"Bad Request","statusCode":400}

Field lạ do schema quyết định: z.object() xoá đi (giống whitelist), z.strictObject() trả lỗi Unrecognized key: "ownerId" (giống forbidNonWhitelisted). Với Valibot (npm install valibot) schema tương đương như sau, câu chữ lỗi sẽ khác:

import * as v from 'valibot';

export const createProjectSchema = v.strictObject({
    name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
    description: v.optional(v.pipe(v.string(), v.maxLength(500))),
});

export type CreateProjectInput = v.InferOutput<typeof createProjectSchema>;

Schema chỉ là thêm một lựa chọn, TaskFlow API giữ DTO class cho body vì dùng mapped types (và Swagger ở Bài 23). Thử xong các bạn xoá code minh hoạ và khởi động lại ứng dụng để dữ liệu trở về hai project mẫu.

6. Lời kết.

Như vậy mình đã giới thiệu với mọi người về validation trong NestJS: ValidationPipe với class-validator và các option của nó, cùng cách kiểm tra bằng Standard Schema với Zod, Valibot. Cả hai đều là pipe, bài sau mình sẽ giới thiệu kỹ hơn về pipe trong NestJS: các pipe có sẵn như ParseIntPipe và cách tự viết pipe.

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