NestJS:转换响应

Posted

技术标签:

【中文标题】NestJS:转换响应【英文标题】:NestJS : transform responses 【发布时间】:2019-10-06 09:46:26 【问题描述】:

使用 NestJS,我们可以使用验证管道转换传入请求 @Body()

同样,我希望使用 https://github.com/typestack/class-transformer classToPlain 转换我的回复。

这样我可以将字段值映射到响应格式,例如:

export class FoobarDto 

    @Transform((money: ExchangeableMoney) => money.localValues)
    public foobar: ExchangeableMoney;


在 NestJS 中实现这一点的惯用方法是什么?

【问题讨论】:

也许你可以使用拦截器。 docs.nestjs.com/interceptors 【参考方案1】:

通常您会将内置的ClassSerializerInterceptorValidationPipe(与transform: true)结合使用。它会在响应中自动调用classToPlain

在您的 dto 中(使用 toPlainOnly):

@Transform((money: ExchangeableMoney) => money.localValues, toPlainOnly: true)
public foobar: ExchangeableMoney;

在您的控制器中:

@UseInterceptors(ClassSerializerInterceptor)

或 globally 在您的 main.ts 中:

app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));

【讨论】:

你好@Kim Kern。有没有办法像使用 ValidationPipe 一样全局打开 ClassSerializerInterceptor? 嗨@JasperBlues!您可以使用main.ts 文件中的useGlobalPipes 方法全局启用任何管道。示例见docs.nestjs.com/pipes#class-validator 太棒了,很好的答案,Kim Kern!感谢@FWoelffel 的评论。 从'@nestjs/core'导入反射器; /* 为什么不直接使用 Reflector */ app.useGlobalInterceptors(new ClassSerializerInterceptor(Reflector));

以上是关于NestJS:转换响应的主要内容,如果未能解决你的问题,请参考以下文章