【问题标题】:NestJS : transform responsesNestJS:转换响应
【发布时间】: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 中实现这一点的惯用方法是什么?

【问题讨论】:

标签: javascript node.js typescript express nestjs


【解决方案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));
猜你喜欢
  • 2019-11-20
  • 2021-12-14
  • 2021-12-28
  • 2019-10-26
  • 2021-04-15
  • 2021-04-10
  • 2019-07-03
  • 2012-02-25
  • 2021-06-26
相关资源
最近更新 更多