Không có sự khác biệt cơ bản nào giữa pipe thông thường và pipe của microservices. Sự khác biệt duy nhất là thay vì throw HttpException, bạn nên dùng RpcException.
Gợi ý Class RpcException được expose từ package @nestjs/microservices.
Gắn pipe (Binding pipes)
Ví dụ sau dùng một pipe method-scoped được khởi tạo thủ công. Giống như với ứng dụng dựa trên HTTP, bạn cũng có thể dùng pipe controller-scoped (nghĩa là, thêm decorator @UsePipes() lên đầu class controller).
@UsePipes(new ValidationPipe({ exceptionFactory: (errors) => new RpcException(errors) }))
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
return (data || []).reduce((a, b) => a + b);
}
@UsePipes(new ValidationPipe({ exceptionFactory: (errors) => new RpcException(errors) }))
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
return (data || []).reduce((a, b) => a + b);
}
Ghi chú người dịch Chi tiết đáng chú ý ở đây là exceptionFactory: khi validation thất bại, ValidationPipe mặc định throw BadRequestException (kiểu HTTP), không phù hợp với ngữ cảnh microservices vốn không có response HTTP. Vì vậy phải tự override để nó throw RpcException thay thế — nếu quên bước này, lỗi validation trong microservice sẽ không được serialize đúng cách về cho client.