midway icon indicating copy to clipboard operation
midway copied to clipboard

@midwayjs/validate 的校验管道没有正确提示缺失字段的key

Open Sakuraine opened this issue 2 years ago • 2 comments

  • Node Version: 14.21.3
  • Midway Version(Decorator/Core): 3.11.6
  • Component Name/Version: @midwayjs/validate
  • Platform:
  • Mini Showcase Repository:

最小复现代码

import { Controller, Get, Query } from '@midwayjs/decorator';
import { ParseIntPipe } from '@midwayjs/validate';

@Controller('/')
export class Controller {
  @Get('/')
  async invoke(@Query('id', [ParseIntPipe]) id: number): Promise<void> {
    //
  }
}

返回结果

{
  "success": false,
  "message": "校验参数错误:\"value\" 是必须的",
  "status": "VALIDATE_10000"
}

预期结果

{
  "success": false,
  "message": "校验参数错误:\"id\" 是必须的",
  "status": "VALIDATE_10000"
}

Sakuraine avatar Jul 20 '23 06:07 Sakuraine

自定义管道也存在这个问题

flyingcrp avatar Oct 30 '23 06:10 flyingcrp

其实这不算Bug,不论是midway提供的还是自定义的管道,都是继承自ParsePipe父类,然后重写getSchema方法返回一个Joi的schema, 对于对象的验证,Joi可以做到参数不合格时指明key,也就是属性名;

管道的验证,一般是用来验证单个数据,例如:number、string ,midway在调用Joi的validate方法时,没有为非Object的校验指定key,所以在报错时,报错信息只会看到value。

这里可以提供一个方案:使用链式lable()函数指定错误信息中的label值。 例如:

@Pipe()
// // 源码:校验number
export class ParseIntPipe extends ParsePipe {
  getSchema(): Joi.AnySchema<any> {
    return Joi.number().integer().required();
  }
}

@Pipe()
export class Test extends ParsePipe{
  protected getSchema() {
    // 指明label
    return super.getSchema().label('id');
  }
}

可以做类似尝试,不算好的方法,但结合midway的源码看,这样的改动小 @cyjake @czy88840616 官方也可以关注下

mmdapl avatar Jan 22 '24 09:01 mmdapl