【问题标题】:How to parse dates in JSON request with NestJs @Body如何使用 NestJs @Body 解析 JSON 请求中的日期
【发布时间】:2020-05-31 01:52:08
【问题描述】:

我有一个如下所示的 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"。如何将此字符串转换为 JavaScript Date 对象?我想将@IsDate 类验证添加到PersonDto,但目前这会失败。

【问题讨论】:

    标签: javascript json date nestjs


    【解决方案1】:

    我想出了如何将全局 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 2016-07-23
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多