我使用NodeJs/NestJs来构建RESTful服务。我创建了一些对象来匹配请求JSON。在这些对象中有一些可选的属性,但如果客户端不通过JSON发送它们,我希望将它们设置为默认值。
实现这一目标的最佳方法是什么?
这是我与JSON匹配的DTO。
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;
}
这是我的NestJs控制器
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
}
}
我启动该服务,并将JSON发布到我的终点
{
"CurrentAge": 40,
}
在我的控制器中,我看到ExistingSavingAmount
是空的,而不是值为0。但是如果我直接实例化RequestDto
,我可以看到ExistingSavingAmount
的值是0。
https://stackoverflow.com/questions/54027807
复制相似问题