【问题标题】:NestJS Serialization - how to instantiate default valuesNestJS 序列化 - 如何实例化默认值
【发布时间】:2021-07-29 05:00:40
【问题描述】:

我的 Nestjs 服务之一中有以下类和枚举

export enum Gender {
    MALE = 'M',
    FEMALE = 'F',
}

export class Address {
  address1: string = '';
  address2: string = '';
  address3: string = '';
  city: string = '';
  state: string = 'TX';
  country: string = 'USA';
}

export class Profile {
  constructor(data?: any) {
        if (data) {
            Object.assign(this, data);
        }
  }

  id: string;
  firstName: string;
  lastName: string;
  email: string;
  gender: Gender;
  address?: Address = new Address();
}

当我使用下面的 new 运算符实例化 Profile 对象时,它会正确填充 address 具有默认值的字段(例如州和国家/地区字段)

让 profile: Profile = new Profile();

我有一个端点 - POST - /profiles

  @Post('profiles')
  @HttpCode(204)
  @ApiResponse({
    status: 204,
    description: 'Audit Entry Created',
  })
  @ApiResponse({
    status: 400,
    description: 'Invalid Audit.',
  })
  @ApiResponse({
    status: 401,
    description: 'Unauthorized Access.',
  })
  @ApiResponse({
    status: 500,
    description: 'System Error.',
  })
  public async create(@Body() profile: Profile): Promise<void> {
    await this.service.create(profile);
  }

在请求正文中采用配置文件 JSON


{
  'id':'123',
  'firstName': 'John',
  'lastName': 'Doe',
  'email':'john.doe@johndoe.com',
  'gender': 'M'
}

当我不传递请求正文的地址部分时,我期待 将使用默认值创建一个默认地址对象,因为我拥有 Profile 类的那一部分。这没有发生。
有什么建议吗?

【问题讨论】:

  • 你在用Nest的ValidationPipe吗?

标签: nestjs nestjs-config


【解决方案1】:

不使用任何转换,传入的正文将只是请求的纯 JSON 表示。要使主体成为Profile 类的实例,您需要使用ValidationPipe 或您自己的自定义管道,并使用传入的主体实例化Profile 类。

否则,@Body() 只是映射到表达或 fastify 的 req.body,它不会为你做任何反序列化

【讨论】:

    【解决方案2】:

    添加@UsePipes(new ValidationPipe({ transform: true }))后解决了这个问题

      @Post('profiles')
      @UsePipes(new ValidationPipe({ transform: true }))
      public async create(@Body() profile: Profile): Promise<void> {
        await this.service.create(profile);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 2020-04-06
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多