With NestJS, we can transform incoming request @Body()
using the validation pipe.
Similarly I would like my responses transformed using https://github.com/typestack/class-transformer classToPlain
.
This is so that I can map field values to the response format, example:
export class FoobarDto {
@Transform((money: ExchangeableMoney) => money.localValues)
public foobar: ExchangeableMoney;
}
What is the idiomatic way to achieve this in NestJS?
Typically you would use the built-in ClassSerializerInterceptor
in combination with the ValidationPipe
(with transform: true
). It automatically calls classToPlain
on the response:
In your dto (with toPlainOnly
):
@Transform((money: ExchangeableMoney) => money.localValues, {toPlainOnly: true})
public foobar: ExchangeableMoney;
In your controller:
@UseInterceptors(ClassSerializerInterceptor)
or globally in your main.ts:
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With