1

我正在用 NestJS 开发 API 和微服务,这是我的控制器功能

    @Post()
    @MessagePattern({ service: TRANSACTION_SERVICE, msg: 'create' })
    create( @Body() createTransactionDto: TransactionDto_create ) : Promise<Transaction>{
        return this.transactionsService.create(createTransactionDto)
    }

当我调用 post api 时,dto 验证工作正常,但是当我使用微服务验证调用它时它不起作用并且它传递给服务而不拒绝错误。这是我的 DTO

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class TransactionDto_create{
    @IsNotEmpty()
    action: string;

    // @IsString()
    readonly rec_id : string;

    @IsNotEmpty()
    readonly data : Object;

    extras : Object;
    // readonly extras2 : Object;
}

当我在没有操作参数的情况下调用 api 时,它显示需要执行错误操作,但是当我使用微服务调用它时

常量模式= {服务:TRANSACTION_SERVICE,味精:'创建'};常量数据 = {id: '5d1de5d787db5151903c80b9', extras:{'asdf':'dsf'}};

return this.client.send<number>(pattern, data)

它不会抛出错误并开始服务。我还添加了 globalpipe 验证。

app.useGlobalPipes(new ValidationPipe({
    disableErrorMessages: false,  // set true to hide detailed error message
    whitelist: false,  // set true to strip params which are not in DTO
    transform: false // set true if you want DTO to convert params to DTO class by default its false
  }));

它如何适用于 api 和微服务,因为我需要在一个地方并具有相同的功能,以便可以根据客户调用它。

4

2 回答 2

3

ValidationPipe 抛出 HTTP BadRequestException,而代理客户端期望 RpcException。

@Catch(HttpException)
export class RpcValidationFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        return new RpcException(exception.getResponse())
    }
}
@UseFilters(new RpcValidationFilter())
@MessagePattern('validate')
async validate(
    @Payload(new ValidationPipe({ whitelist: true })) payload: SomeDTO,
) {
    // payload validates to SomeDto 
    . . .
}
于 2020-06-26T23:31:35.940 回答
0

我会四处走动,假设main.ts你有电话线app.useGlobalPipes(new ValidationPipe());从文档

对于混合应用程序,该useGlobalPipes()方法不会为网关和微服务设置管道。对于“标准”(非混合)微服务应用程序,useGlobalPipes()是否在全球范围内安装管道。

您可以改为从 全局绑定管道AppModule,或者您可以@UsePipes()在需要通过验证的每条路由上使用装饰器ValidationPipe

在此处绑定管道的更多信息

于 2019-07-04T18:41:27.153 回答