| 1 | /* |
| 2 | * @Author: niuwenzheng |
| 3 | * @Date: 2020-04-14 15:29:18 |
| 4 | * @LastEditors: nevin |
| 5 | * @LastEditTime: 2025-01-15 14:29:42 |
| 6 | * @Description: 参数验证管道 |
| 7 | */ |
| 8 | import { |
| 9 | PipeTransform, |
| 10 | Injectable, |
| 11 | ArgumentMetadata, |
| 12 | BadRequestException, |
| 13 | } from '@nestjs/common'; |
| 14 | import { validateSync } from 'class-validator'; |
| 15 | import { plainToClass } from 'class-transformer'; |
| 16 | import * as _ from 'lodash'; |
| 17 | |
| 18 | @Injectable() |
| 19 | export class ParamsValidationPipe implements PipeTransform<any> { |
| 20 | private toValidate(metatype): boolean { |
| 21 | const types = [String, Boolean, Number, Array, Object]; |
| 22 | return !types.includes(metatype); |
| 23 | } |
| 24 | |
| 25 | async transform(value: any, { metatype }: ArgumentMetadata) { |
| 26 | if (!metatype || !this.toValidate(metatype)) return value; |
| 27 | |
| 28 | // 数据转换成类 |
| 29 | const inData: any = plainToClass(metatype, value, { |
| 30 | excludeExtraneousValues: true, |
| 31 | }); |
| 32 | |
| 33 | const errors = validateSync(inData, { |
| 34 | whitelist: true, |
| 35 | }); |
| 36 | |
| 37 | if (errors.length <= 0) return inData; |
| 38 | console.log('------ 参数验证失败:', _.values(errors[0].constraints)[0]); |
| 39 | |
| 40 | throw new BadRequestException( |
| 41 | '参数验证失败: ' + _.values(errors[0].constraints)[0], |
| 42 | ); |
| 43 | } |
| 44 | } |
| 45 |