Microservices

管道

学习如何在 NestJS 微服务中使用管道进行数据验证和转换

管道

常规管道 和微服务管道之间没有根本区别。唯一的区别是,您应该使用 RpcException 而不是抛出 HttpException

提示 RpcException 类从 @nestjs/microservices 包导出。

绑定管道

以下示例使用手动实例化的方法作用域管道。就像基于 HTTP 的应用程序一样,您也可以使用控制器作用域管道(即,在控制器类前加上 @UsePipes() 装饰器)。

@@filename()
@UsePipes(new ValidationPipe({ exceptionFactory: (errors) => new RpcException(errors) }))
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
  return (data || []).reduce((a, b) => a + b);
}
@@switch
@UsePipes(new ValidationPipe({ exceptionFactory: (errors) => new RpcException(errors) }))
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
  return (data || []).reduce((a, b) => a + b);
}