NestJS,在 DTO 中序列化 bigint 参数

问题描述

我有带有 bigint 类型参数的 DTO。目前,当我收到这些 DTO 时,所有这些 pramaters 的类型总是 string。示例如下:

@Get("")
async foo(@Query() query: Foo) {
    console.log(typeof Foo.amount) //string
}

我的 DTO:

export class Foo { 
    amount: bigint;
}

如何使其工作并拥有 bigint 类型的 amount

解决方法

在您的 DTO 中:

import { Transform } from 'class-transformer';

//...

export class Foo { 
    @Transform(val => BigInt(val.value))
    amount: bigint;
}

也在您的控制器中:

import {ValidationPipe} from '@nestjs/common';

//...

@Get("")
async foo(@Query(new ValidationPipe({ transform: true })) query: Foo) {
    console.log(typeof Foo.amount) //should be bigint
}

发生了什么:

ValidationPipe 是 NestJS 中的默认管道,它使用反射来使用 Foo DTO 类中定义的规则来验证查询属性。选项 transform: true 将转换即;在 @Transform 装饰器中执行函数并用转换后的值替换原始值(在您的情况下为 val => BigInt(val))。

这会将字符串化的“bigint”转换为原始的“bigint”。

编辑:更新了 Transform 装饰器内的函数以匹配 class-transformer v0.4.0