44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
|
|
import {
|
||
|
|
PipeTransform,
|
||
|
|
Injectable,
|
||
|
|
ArgumentMetadata,
|
||
|
|
BadRequestException,
|
||
|
|
} from '@nestjs/common';
|
||
|
|
import { validate } from 'class-validator';
|
||
|
|
import { plainToInstance } from 'class-transformer';
|
||
|
|
import { ErrorCode } from '../interfaces/response.interface';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 全局验证管道
|
||
|
|
* 自动验证 DTO 并返回统一格式的错误
|
||
|
|
*/
|
||
|
|
@Injectable()
|
||
|
|
export class ValidationPipe implements PipeTransform<any> {
|
||
|
|
async transform(value: any, { metatype }: ArgumentMetadata) {
|
||
|
|
if (!metatype || !this.toValidate(metatype)) {
|
||
|
|
return value;
|
||
|
|
}
|
||
|
|
|
||
|
|
const object = plainToInstance(metatype, value);
|
||
|
|
const errors = await validate(object);
|
||
|
|
|
||
|
|
if (errors.length > 0) {
|
||
|
|
const messages = errors
|
||
|
|
.map((error) => Object.values(error.constraints || {}).join(', '))
|
||
|
|
.join('; ');
|
||
|
|
|
||
|
|
throw new BadRequestException({
|
||
|
|
code: ErrorCode.PARAM_ERROR,
|
||
|
|
message: messages,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
return object;
|
||
|
|
}
|
||
|
|
|
||
|
|
private toValidate(metatype: Function): boolean {
|
||
|
|
const types: Function[] = [String, Boolean, Number, Array, Object];
|
||
|
|
return !types.includes(metatype);
|
||
|
|
}
|
||
|
|
}
|