使用 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/