- 基于 NestJS + TypeScript + MySQL + Redis 架构 - 完整的模块化设计(认证、用户、小组、游戏、预约等) - JWT 认证和 RBAC 权限控制系统 - Docker 容器化部署支持 - 添加 CLAUDE.md 项目开发指南 - 配置 .gitignore 忽略文件 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
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);
|
|
}
|
|
}
|