Artem
Artem

Reputation: 397

NestJS, serialise bigint parameters in DTO

I have DTOs with parameters which have bigint type. Currently, when I receive these DTOs all these pramaters always have type string. Here is example:

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

My DTO:

export class Foo { 
    amount: bigint;
}

How to make it works and have bigint type of amount

Upvotes: 0

Views: 3875

Answers (1)

SPS
SPS

Reputation: 943

In your DTO:

import { Transform } from 'class-transformer';

//...

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

Also in your controller:

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

//...

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

Whats Happening:

ValidationPipe is a default pipe in NestJS that validates query property with the rules defined in Foo DTO class using Reflection. The option transform: true will transform ie; execute the function inside @Transform decorator and replace the original value with the transformed value (val => BigInt(val) in your case).

This will transform the stringified "bigint" to the primitive "bigint".

EDIT: Updated the function inside Transform decorator to match class-transformer v0.4.0

Upvotes: 3

Related Questions