简体   繁体   中英

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.

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;
}

To expand upon this answer a bit, you can also define a new ValidationPipe in the @Body() decorator in requests which need this type of parsing.

  @Post()
  async create(
    @Body(new ValidationPipe({ transform: true }))
    collectibleDto: CreateCollectibleDto,
  ): Promise<void> {
    return this.collectibleService.create(collectibleDto);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM