我使用 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 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
}
}
我启动服务,并将以下 JSON 发布到我的端点
{
"CurrentAge": 40,
}
在我的 Controller 中,我看到 ExistingSavingAmount
为空,而不是值为 0。但是,如果我直接实例化 RequestDto
,我可以看到 ExistingSavingAmount 的值
是 0。
最佳答案
仅当 RequestDto
实际上实例化为类时,您的默认值才会适用。由于您已经使用 class-validator 进行验证,因此可以使用 classTransformer.plainToClass()
实例化该类。
如果您使用内置的 ValidationPipe
,则可以使用 { transform: true }
选项来自动实例化您的 RequestDto
类:
@UsePipes(new ValidationPipe({ transform: true }))
@Post('MyEndPoint')
public doSomething(@Body() request: RequestDto) {
或作为全局管道:
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.useGlobalPipes(new ValidationPipe({ transform: true }));
await app.listen(3000);
}
bootstrap();
关于node.js - 有没有办法将默认值设置为缺失/可选 JSON 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54027807/