Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Jasper Blues Avatar asked May 20 '19 03:05

Jasper Blues


1 Answers

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)));
like image 61
Kim Kern Avatar answered Oct 12 '22 15:10

Kim Kern