Search code examples
javascriptnode.jstypescriptexpressnestjs

NestJS : transform responses


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?


Solution

  • 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)));