gpt4 book ai didi

javascript - ValidationPipe() 不适用于 Nestjs/Crud 中的重写 @Query

转载 作者:行者123 更新时间:2023-12-05 06:52:30 24 4
gpt4 key购买 nike

我正在尝试验证 get 请求查询中的参数,但出于某种原因,验证管道无法识别查询的元素。

import {
Controller,
Post,
Query,
Body,
UseInterceptors,
Param,
Res,
Logger,
} from '@nestjs/common';
import { Crud, CrudController, Override } from '@nestjsx/crud';

import { OpenScheduleDto } from './open-schedule.dto';
@Crud(Schedule)
export class ScheduleController
implements CrudController<ScheduleService, Schedule> {
constructor(public service: ScheduleService) {}

get base(): CrudController<ScheduleService, Schedule> {
return this;
}

@Override()
async getMany(@Query() query: OpenScheduleDto) {
return query;
}
}

OpenSchedule.dto

import { IsNumber, IsOptional, IsString } from 'class-validator';
export class OpenScheduleDto {

@IsNumber()
companyId: number;

@IsNumber()
@IsOptional()
professionalId: number;

@IsString()
@IsOptional()
scheduleDate: string;
}

当我向 http://localhost:3000/schedules?companyId=3&professionalId=1 发出获取请求时

我收到意外错误:

{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"companyId": "3",
"professionalId": "1"
},
"value": "3",
"property": "companyId",
"children": [],
"constraints": {
"isNumber": "companyId must be a number"
}
},
{
"target": {
"companyId": "3",
"professionalId": "1"
},
"value": "1",
"property": "professionalId",
"children": [],
"constraints": {
"isNumber": "professionalId must be a number"
}
}
]
}

最佳答案

那是因为当你使用@Query参数时,一切都是字符串。它没有数字或 bool 值作为数据类型,如 json。因此,您必须先将您的值(value)转换为数字。为此,您可以使用 class-transformer@Transform:

import { IsNumber, IsOptional, IsString } from 'class-validator';
import { Transform } from 'class-transformer';
export class OpenScheduleDto {

@Transform(id => parseInt(id))
@IsNumber()
companyId: number;

@Transform(id => id ? parseInt(id) : id)
@IsNumber()
@IsOptional()
professionalId?: number;

@IsString()
@IsOptional()
scheduleDate?: string;
}

但请注意,这是不安全的,因为例如parseInt('5abc010')5。因此,您可能希望在转换函数中进行额外检查。

关于javascript - ValidationPipe() 不适用于 Nestjs/Crud 中的重写 @Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65955723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com