ValidationPipe()在Nestjs / Crud中的覆盖@Query上不起作用

时间:2019-03-29 18:47:30

标签: javascript node.js typescript nestjs class-validator

我正在尝试验证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"
            }
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

这是因为当您使用@Query参数时,所有内容都是字符串。它没有数字或布尔值作为json之类的数据类型。因此,您必须先将值转换为数字。为此,您可以使用class-transformer的{​​{1}}:

@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 => parseInt(id)) @IsNumber() @IsOptional() professionalId: number; @IsString() @IsOptional() scheduleDate: string; } parseInt('5abc010')。因此,您可能需要对转换函数进行其他检查。