NestJS 搭建博客系统(五)— 使用class-validator+类验证器实现表单验证
前言
上一章节我们使用了拦截器和异常过滤器实现了请求返回的格式化,也在getOne方法做了一个错误响应,这一节,我们使用 类验证器 + class-validator + dto 实现表单验证
安装依赖
yarn add class-validator class-transformer
使用类验证器
全局使用 类验证器
修改 main.ts 类
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-execption.filter';
import { TransformInterceptor } from './interceptor/transform.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe())
app.useGlobalInterceptors(new TransformInterceptor())
app.useGlobalFilters(new HttpExceptionFilter())
await app.listen(3000);
}
bootstrap();
修改异常过滤器,把错误信息返回
// src/filters/http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import { execPath } from 'process';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const message = exception.message
const exceptionResponse: any = exception.getResponse()
let validatorMessage = exceptionResponse
if (typeof validatorMessage === 'object') {
validatorMessage = exceptionResponse.message[0]
}
response
.status(status)
.json({
code: status,
message: validatorMessage || message,
});
}
}
新增一个工具类存放常用正则表达式,稍后会用到
// src/utils/regex.util.ts
// 非 0 正整数
export const regPositive: RegExp = /^[1-9]\d*$/
修改 article 的 dto
// src/modules/article/dto/list.dto.ts
import { Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";
export class ListDTO {
@Matches(regPositive, { message: 'page 不可小于 0' })
readonly page?: number;
@Matches(regPositive, { message: 'pageSize 不可小于 0' })
readonly pageSize?: number;
}
// src/modules/article/dto/id.dto.ts
import { IsNotEmpty, Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";
export class IdDTO {
@Matches(regPositive, { message: '请输入有效 id' })
@IsNotEmpty({ message: 'id 不能为空' })
readonly id: number
// src/modules/article/dto/id.dto.ts
import { IsNotEmpty, Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";
export class IdDTO {
@Matches(regPositive, { message: '请输入有效 id' })
@IsNotEmpty({ message: 'id 不能为空' })
readonly id: number
// src/modules/article/dto/article-create.dto.ts
import { IsNotEmpty } from "class-validator";
export class ArticleCreateDTO {
@IsNotEmpty({ message: '请输入文章标题' })
readonly title: string;
@IsNotEmpty({ message: '请输入文章描述' })
readonly description: string;
@IsNotEmpty({ message: '请输入文章内容' })
readonly content: string;
}
// src/modules/article/dto/article-edit.dto.ts
import { IsNotEmpty, Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";
import { ArticleCreateDTO } from "./article-create.dto";
export class ArticleEditDTO extends ArticleCreateDTO {
@Matches(regPositive, { message: '请输入有效 id' })
@IsNotEmpty({ message: 'id 不能为空' })
readonly id: number
}
至此,我们实现了article所有接口的表单验证