har*_*ang 3 json node.js typescript nestjs
我使用 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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
我启动该服务,并将以下 JSON 发布到我的端点
{
"CurrentAge": 40,
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我看到的ExistingSavingAmount是空白而不是 0。但是如果我RequestDto直接实例化,我可以看到 的值为ExistingSavingAmount0。
RequestDto仅当实际实例化为类时,您的默认值才会适用。由于您已经使用类验证器进行验证,因此您可以使用它 classTransformer.plainToClass()来实例化该类。
如果您使用内置的ValidationPipe,您可以使用该{ transform: true }选项来自动实例化您的RequestDto类:
@UsePipes(new ValidationPipe({ transform: true }))
@Post('MyEndPoint')
public doSomething(@Body() request: RequestDto) {
Run Code Online (Sandbox Code Playgroud)
或作为全局管道:
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.useGlobalPipes(new ValidationPipe({ transform: true }));
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)