javascript - NestJS : transform responses

标签 javascript node.js typescript express nestjs

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

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

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

export class FoobarDto {

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

}

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

最佳答案

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

在你的 dto 中(使用 toPlainOnly):

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

在你的 Controller 中:

@UseInterceptors(ClassSerializerInterceptor)

globally在你的 main.ts 中:

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

关于javascript - NestJS : transform responses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213878/

相关文章:

javascript - 将对象转换为格式化的可读文本

reactjs - 如何设置react-router-dom的类型?

javascript - typescript 错误 :Type 'number' is not assignable to type 'never'

javascript - 如何在 Lambda 函数中定义 emit() 属性

javascript - Node.js - 语法错误 : Unexpected token import while running on node 6. 10.2

reactjs - Webpack css-loader 失败 : "You may need an appropriate loader to handle this file type."

javascript - 切换多个类

javascript - 如何通过for循环将项目分成3列?

javascript - 为什么不能像 html/javascript 中的 document.body.div[0] 一样访问 body 的第一个 div 元素

javascript - 部分代码未触发 focusout 事件