NestJS:转换响应

Jas*_*ues 6 javascript node.js express typescript nestjs

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

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

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

export class FoobarDto {

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

}
Run Code Online (Sandbox Code Playgroud)

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

Kim*_*ern 8

通常,您会将内置ClassSerializerInterceptor函数与ValidationPipe(with transform: true)结合使用。它会自动调用classToPlain响应:

在您的 dto (with toPlainOnly) 中:

@Transform((money: ExchangeableMoney) => money.localValues, {toPlainOnly: true})
public foobar: ExchangeableMoney;
Run Code Online (Sandbox Code Playgroud)

在您的控制器中:

@UseInterceptors(ClassSerializerInterceptor)
Run Code Online (Sandbox Code Playgroud)

或在您的 main.ts 中全局

app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
Run Code Online (Sandbox Code Playgroud)