0

我的 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 对象时,它会 使用默认值(例如州和国家/地区字段)正确填充地址字段

让配置文件:配置文件=新配置文件();

我有一个端点 - 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 类的那部分。这没有发生。
有什么建议么?

4

2 回答 2

0

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

否则,@Body()只需映射到 express 或 fastifyreq.body不会为您进行任何反序列化

于 2021-06-29T16:57:39.440 回答
0

添加@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);
  }
于 2021-07-28T21:00:40.800 回答