Pipe phân tích cú pháp
Thuộc phần TypeScript và NestJS trong hành trình Node.js của Coddy. Bài học 17 trên 24.
GET /tasks/abc trả về 404 "Task NaN not found", nhưng abc vốn không phải là id: đây là yêu cầu không hợp lệ, 400. Pipe có thể chuyển đổi cũng như kiểm tra.
@Get()
findAll(@Query('year', ParseIntPipe) year: number) {
return this.reportsService.forYear(year);
}Khi được truyền làm đối số thứ hai của decorator tham số, ParseIntPipe chuyển văn bản thành số trước khi phương thức chạy. GET /reports?year=2026 truyền số 2026, nên cuối cùng year: number là đúng; ?year=soon trả về 400 "Validation failed (numeric string is expected)" và phương thức không chạy. ParseBoolPipe và ParseUUIDPipe hoạt động tương tự.
Thử thách
DễGET /tasks/abcvàDELETE /tasks/abctrả về 400.- Các id dạng số vẫn hoạt động như trước; id không tồn tại vẫn trả về 404.
- Gửi
GET /tasks/abc, sau đóGET /tasks/1, rồiGET /tasks/9999.
Tự làm thử
import { Body, Controller, Delete, Get, HttpCode, Inject, Param, Post, Query } from '@nestjs/common';
import { CreateTaskDto } from './dto/create-task.dto';
import { Task, TasksService } from './tasks.service';
@Controller('tasks')
export class TasksController {
constructor(
private readonly tasksService: TasksService,
@Inject('PAGE_SIZE') private readonly pageSize: number,
) {}
@Get()
findAll(@Query('done') done?: string, @Query('page') page = '1') {
const tasks = this.tasksService.findAll(done);
const current = Number(page);
const start = (current - 1) * this.pageSize;
return {
items: tasks.slice(start, start + this.pageSize),
page: current,
total: tasks.length,
pages: Math.ceil(tasks.length / this.pageSize),
};
}
@Get(':id')
findOne(@Param('id') id: string): Task {
return this.tasksService.findOne(Number(id));
}
@Post()
create(@Body() dto: CreateTaskDto): Task {
return this.tasksService.create(dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id') id: string): void {
this.tasksService.remove(Number(id));
}
}
Tất cả bài học trong TypeScript và NestJS
Tự luyện tập: Playground Express