Nest 使用 DTO
安装
bash
pnpm i class-validator class-transformer -S修改 global.pipe.ts
ts
import { PipeTransform, Injectable, ArgumentMetadata } from "@nestjs/common";
import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";
// 引入我自己验证的异常类
import { GlobalCheckException } from "./globalcheck.exception";
@Injectable()
export class GlobalPipe implements PipeTransform {
// 校验类型
private toValidate(metatype: Function): boolean {
// 其他类型不验证
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
// 变成对象,把规则和值 组合成验证的对象
const object = plainToInstance(metatype, value);
// 验证 errors 是个数组
const errors = await validate(object);
if (errors.length > 0) {
// 第一种只返回第一个
if (errors.length == 1) {
for (let arr in errors[0].constraints) {
const result = `${errors[0].constraints[arr]}`;
throw new GlobalCheckException(result);
}
}
// 第二种返回所有
let result: string[] = [];
errors.forEach((item) => {
for (let arr in item.constraints) {
result.push(item.constraints[arr]);
}
});
throw new GlobalCheckException(result.join("|"));
}
return value;
}
}新建一个 DTO
ts
import { IsNotEmpty, MaxLength, MinLength } from "class-validator";
export class CreateUserDto {
@MinLength(6, { message: "userId不能小于6位" })
@IsNotEmpty({ message: "userId不能为空" })
userId: string;
@IsNotEmpty({ message: "userName不能为空" })
@MaxLength(20, { message: "userName长度不能超过20位" })
@MinLength(6, { message: "userName长度不能小于6位" })
userName: string;
}控制器使用
ts
@Post('register/jwt')
async createJwt(@Body() body: CreateUserDto) {
const token = await this.JwtServiceAll.setToken({
userId: body.userId,
userName: body.userName,
});
return {
data: token,
};
}