在 NestJS 中使用和包描述 DTO 类时,有没有办法设置装饰器的执行顺序?class-validatorclass-transformer
当 的值foo设置为时,以下代码会失败null并出现错误:
需要一个字符串,但收到一个 null
@IsOptional()
@IsString()
@IsByteLength(1, 2048)
@Transform(({ value }) => validator.trim(value))
@Transform(({ value }) => validator.stripLow(value))
foo: string;
Run Code Online (Sandbox Code Playgroud)
即使我有一个isString装饰器应该检查是否确实传递了一个字符串,并且必须已经失败而不将执行传递给装饰@Transform器,但它并没有失败。
decorator typescript class-validator nestjs class-transformer
是否可以在 nestJs(类验证器 => 自定义验证器)中注入执行上下文或访问当前请求?
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
import { Injectable } from '@nestjs/common';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';
@ValidatorConstraint({ name: 'modelExistsConstraint', async: true })
@Injectable()
export class ModelExistsConstraint implements ValidatorConstraintInterface {
constructor(
@InjectConnection('default') private readonly connection: Connection,
) {
}
async validate(value: string, validationArguments: ValidationArguments) {
// here need request or execution context;
// const test = this.context.switchToHttp().getRequest();
const model = await this.connection
.getRepository(validationArguments.constraints[0])
.findOne({ where: { [validationArguments.property]: …Run Code Online (Sandbox Code Playgroud) ValidationPipe我使用带有选项的全局{ transform: true, whitelist: true }。但是,在特定的控制器请求中,我想重用相同的类但具有不同的验证,应用类验证器的验证组技术。因此,我有必要覆盖管道的选项以应用新选项。
这是在 NestJS 6.2.4 上。我尝试在 处应用新管道@Query(new ValidationPipe({groups: ['res']})),但全局管道仍然应用。我应用了相同的逻辑,@UsePipes()但再次应用了全局管道。
另外,我尝试将always: false属性与组一起应用,以避免始终验证属性,但由于这是默认行为,因此没有太大帮助。
@IsNumberString({ groups: ['res'] })
resId: number;
Run Code Online (Sandbox Code Playgroud) 我有一个 NestJS 项目,其中同时使用类验证器和类转换器,并且我需要在类验证器抛出错误之前执行类转换器。
给定以下课程:
export class CreateProfileDto {
@IsString()
@Expose({ name: 'name' })
profileName!: string;
@IsBoolean()
@Expose({ name: 'active'})
profileActive!: boolean;
}
Run Code Online (Sandbox Code Playgroud)
我需要用属性名称而不是属性 profileName 来公开错误,其他属性也是如此。
有什么直接的想法来管理这个吗?无法要求前端向我发送具有不同名称的属性,这就是我需要调整它们的原因。
我想通过管道来做到这一点,但在错误爆发之前无法使用它。
当前错误格式:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"profileName": 1
},
"value": 1,
"property": "profileName",
"children": [],
"constraints": {
"isString": "profileName must be a string"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
所需的错误格式:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"name": 1
},
"value": 1,
"property": "name",
"children": …Run Code Online (Sandbox Code Playgroud) 我正在尝试将验证插入 PUT 请求中。
DTO 的:
export class SettingUpdateDto implements ISettingUpdate {
@IsInt()
@IsPositive()
id: number;
@IsNotEmpty()
@IsString()
value: string;
}
export class SettingArrayUpdateDto {
@Type(() => SettingUpdateDto)
@ValidateNested({ each: true })
items: SettingUpdateDto[];
}
Run Code Online (Sandbox Code Playgroud)
控制器
@Put()
async updateItem(@Body() items: SettingArrayUpdateDto) {
return await this.dataService.update(items);
}
Run Code Online (Sandbox Code Playgroud)
服务
async update(items: SettingArrayUpdateDto[]): Promise<Setting> {
console.log("service data", items);
return <Setting>{}; <SettingUpdateDto[]>items;
}
Run Code Online (Sandbox Code Playgroud)
当我发送数据时,像这样:
[
{"id": -20, "value": {"name": "333"}},
{"id": 21, "value": "2222222222222222"}
]
Run Code Online (Sandbox Code Playgroud)
我收到空数组。我究竟做错了什么?错误在哪里?
当我将控制器中的设置从SettingArrayUpdateD更改为任意时,控制器收到原始请求数据。
NestJs 6.10.14 版本。
我正在尝试在 Nestjs 中使用 DTO 验证对象数组。我已经尝试过,但数据未得到验证。我尝试搜索很多但没有得到任何答案。这些是我的文件:
trivia.controller.ts 文件
import { Controller, Post, Body, ParseArrayPipe } from '@nestjs/common';
import { LoggerService } from '../logger/logger.service';
import { TriviaService } from './trivia.service';
import { PostTriviaScoreDto } from './dto/post-trivia-score.dto';
@Controller('trivia')
export class TriviaController {
constructor(private readonly logger: LoggerService, private readonly triviaService: TriviaService) {}
@Post('score')
postTriviaScore(@Body(new ParseArrayPipe({ items: PostTriviaScoreDto })) postTriviaScoreDto: PostTriviaScoreDto) {
this.logger.info('Trivia Controller : postTriviaScore : start');
return this.triviaService.postTriviaScore(postTriviaScoreParamsDto, postTriviaScoreDto);
}
}
Run Code Online (Sandbox Code Playgroud)
trivia.service.ts 文件
import { LoggerService } from '../logger/logger.service';
import { PostTriviaScoreDto } …Run Code Online (Sandbox Code Playgroud) 我的大多数 NestJs 控制器看起来都一样。它们具有基本的 CRUD 功能并执行完全相同的操作。
控制器之间的唯一区别是:
下面是一个 CRUD 控制器示例:
@UseGuards(JwtAuthGuard)
@Controller("/api/warehouse/goods-receipts")
export class GoodsReceiptsController
implements ICrudController<GoodsReceipt, CreateGoodsReceiptDto, UpdateGoodsReceiptDto, QueryGoodsReceiptDto> {
constructor(private service: GoodsReceiptsService) {
}
@Post()
create(@Body() body: CreateGoodsReceiptDto, @CurrentUser() user: Partial<User>): Promise<GoodsReceipt> {
return this.service.createItem(body, user);
}
@Delete(":id")
delete(@Param() params: NumberIdDto): Promise<Partial<GoodsReceipt>> {
return this.service.deleteItem(params.id);
}
@Get(":id")
getOne(@Param() params: NumberIdDto): Promise<GoodsReceipt> {
return this.service.getItem(params.id);
}
@Get()
get(@Query() query: QueryGoodsReceiptDto): Promise<GoodsReceipt[]> {
return this.service.getItems(query);
}
@Patch()
update(@Body() body: UpdateGoodsReceiptDto, @CurrentUser() user: Partial<User>): Promise<GoodsReceipt> {
return …Run Code Online (Sandbox Code Playgroud) 我是 NestJS 的新手,我正在尝试从查询参数中填充过滤器 DTO。
这是我所拥有的:
询问:
本地主机:3000/api/checklists?stations=114630,114666,114667,114668
控制器
@Get()
public async getChecklists(@Query(ValidationPipe) filter: ChecklistFilter): Promise<ChecklistDto[]> {
// ...
}
Run Code Online (Sandbox Code Playgroud)
DTO
export class ChecklistFilter {
@IsOptional()
@IsArray()
@IsString({ each: true })
@Type(() => String)
@Transform((value: string) => value.split(','))
stations?: string[];
// ...
}
Run Code Online (Sandbox Code Playgroud)
有了这个,类验证器不会抱怨,然而,在过滤器对象中,站实际上不是一个数组,而是一个单一的字符串。
我想将其转换为验证管道中的数组。我怎样才能做到这一点?
我正在使用类验证器来验证数据,我需要实现文件上传的验证。例如:文件不为空(如果还实现文件必须是图像,那就太好了)。
我尝试通过以下方式:
export class FileModel extends Model {
@IsNotEmpty()
file: File
constructor(body: any) {
super();
const {
file,
} = body;
this.file = file;
}
}
Run Code Online (Sandbox Code Playgroud)
但即使我选择文件,它总是返回“文件不应为空”。有没有办法实现文件上传的验证。
提前致谢 :)
如何使用类验证器检查数组是否为空。
下面给出的是我的结构。我想检查cartId是否为空。
{
"cartId": []
}
Run Code Online (Sandbox Code Playgroud) class-validator ×10
nestjs ×8
typescript ×7
validation ×3
arrays ×2
node.js ×2
decorator ×1
dto ×1