I use NodeJs/NestJs to build a RESTful service. I created some object to match with the request JSON. In these objects there are some optional attributes, but I would like to set default values to them if the client does not send them via JSON.
What is the best way to achieve the goal?
This is my DTO to match with JSON.
import { IsDefined, IsNumber, Min } from 'class-validator';
import { ApiModelProperty, ApiModelPropertyOptional } from '@nestjs/swagger';
export class RequestDto {
@IsDefined()
@IsNumber()
@Min(0)
@ApiModelProperty({description: 'The current age.'})
public CurrentAge: number;
@ApiModelPropertyOptional({description: 'The existing saving amount.'})
public ExistingSavingAmount: number = 0;
}
This is my NestJs controller
import { Controller, Post, Body, Param } from '@nestjs/common';
import { RequestDto } from './Dto/Request.Dto';
import { ApiResponse, ApiOperation } from '@nestjs/swagger';
@Controller('mycontroller')
export class MyController {
@Post('MyEndPoint')
@ApiOperation({ title: 'Do something' })
@ApiResponse({ status: 201, description: 'Something is done' })
public doSomething(@Body() request: RequestDto) {
// do more jobs
}
}
I launch the service, and post following JSON to my end point
{
"CurrentAge": 40,
}
In my controller I see ExistingSavingAmount is blank in stead of having value of 0. But if I instantiate the RequestDto directly I could see the value of ExistingSavingAmount is 0.