Search code examples
nestjsnestjs-config

NestJS Serialization - how to instantiate default values


I have the following classes and enum in one of my nestjs service

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

When I instantiate a Profile object with new operator like below, it correctly populates address field with default values (e.g.state and country fields)

let profile: Profile = new Profile();

I have an end-point - 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);
  }

which takes profile JSON in request body


{
  'id':'123',
  'firstName': 'John',
  'lastName': 'Doe',
  'email':'[email protected]',
  'gender': 'M'
}

When i don't pass address part of request body, i am expecting a default address object will be created with the default values as I have that part of Profile class. Which is not happening.
Any suggestions?


Solution

  • Without using any transformations, the incoming body will just be a plain JSON representation of the request. To get the body to be an instance of the Profile class, you'd need to use the ValidationPipe, or a custom pipe of your own, and instantiate the Profile class using the incoming body.

    Otherwise, @Body() just maps to express or fastify's req.body which won't do any de-serialization for you