如何用NestJs@Body解析JSON请求中的日期

2022-03-07 json date javascript nestjs

我有一个DTO,如下所示:

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

我的NestJs控制器方法如下所示:

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

发布的JSON数据具有birthDate作为字符串:"2020-01-15"。如何将此字符串转换为JavaScriptDate对象?我想将@IsDate类验证添加到PersonDto,但目前该操作将失败。


解决方案

我了解了如何将全局ValidationPipe与Date属性和@IsDate()批注一起使用:

第一步是允许这样的转换(以我的引导文件为例):

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

然后您需要使用@Type()批注来批注DTO:

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

class PersonDto {
   readonly name: string;
   @Type(() => Date)
   @IsDate()
   readonly birthDate: Date;
}

相关文章