Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse dates in JSON request with NestJs @Body

I have a DTO that looks like this:

class PersonDto {
   readonly name: string;
   readonly birthDate: Date;
}

My NestJs controller method looks like this:

@Post
create(@Body() person: PersonDto) {
    console.log("New person with the following data:", person);
    // more logic here
}

The JSON data that gets posted has birthDate as a string: "2020-01-15". How can I convert this string to a JavaScript Date object? I'd like to add the @IsDate class-validation to PersonDto but currently that would fail.

like image 225
chiborg Avatar asked Feb 15 '20 15:02

chiborg


1 Answers

I figured out how to use the global ValidationPipe with a Date property and the @IsDate() annotation:

The first step is to allow transformations like this (my bootstrap file as an example):

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({transform: true}));
  await app.listen(3000);
}
bootstrap();

Then you need to annotate the DTO with the @Type() annotation:

import { IsDate } from 'class-validator';
import { Type } from 'class-transformer';

class PersonDto {
   readonly name: string;
   @Type(() => Date)
   @IsDate()
   readonly birthDate: Date;
}
like image 53
chiborg Avatar answered Oct 12 '22 19:10

chiborg