Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sakuraine opened this issue Jul 20, 2023 · 2 comments
Open

Comments

@Sakuraine
Copy link
Contributor

  • 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"
}
@flyingcrp
Copy link
Contributor

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

@mmdapl
Copy link
Contributor

mmdapl commented Jan 22, 2024

其实这不算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 官方也可以关注下

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants