javascript - NestJS:轉換回應
使用 NestJS,我們可以使用驗證管道轉換傳入的請求 @Body()。
同樣地,我也希望我的回應能使用 https://github.com/typestack/class-transformer classToPlain 進行轉換。
這是為了讓我可以將欄位值對應到回應格式,例如:
export class FoobarDto {
@Transform((money: ExchangeableMoney) => money.localValues)
public foobar: ExchangeableMoney;
}
在 NestJS 中實現這個的慣用方法是什麼?
答案#1
通常你會將內建的 ClassSerializerInterceptor 與 ValidationPipe(設定 transform: true)一起使用。它會自動在回應上呼叫 classToPlain:
在你的 DTO(使用 toPlainOnly):
@Transform((money: ExchangeableMoney) => money.localValues, {toPlainOnly: true})
public foobar: ExchangeableMoney;
在你的控制器中:
@UseInterceptors(ClassSerializerInterceptor)
或者在你的 main.ts 中全局使用:
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
