Nest 实战 (三)
Nest 使用全局管道和 全局过滤器
全局管道
安装依赖
bash
pnpm i class-validator class-transformer -S
设置全局
main.ts
里面引入过滤器
js
// 开启全局管道
// 全局验证器
import { ValidationPipe } from "@nestjs/common";
// transform:true 自动将传入的数据转换为相应的DTO(数据传输对象)类型。
// whitelist:true 过滤掉DTO中没有声明的属性。
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
全局过滤器
新建文件
src/common/filters/http-exception.filter.ts
js
import {
Catch,
HttpException,
ExceptionFilter,
ArgumentsHost,
HttpStatus,
} from "@nestjs/common";
@Catch(HttpException)
export class HttpExceptionsFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = exception.getStatus();
console.log(status);
//exception.getStatus();
const exceptionResponse = exception.getResponse();
let message = exceptionResponse.message ?? "服务错误";
if (status == 404) {
message = "资源不存在";
}
if (exceptionResponse?.message instanceof Array) {
message = exceptionResponse.message[0];
}
response.status(200).json({
code: status,
msg: message,
data: null,
});
}
}
设置全局
main.ts
里面引入过滤器
js
// 全局过滤器
import { HttpExceptionsFilter } from "src/common/filters/http-exceptions-filter";
// 开启全局过滤器
app.useGlobalFilters(new HttpExceptionsFilter());
全部
js
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import rateLimit from "express-rate-limit";
// 配置文件
import { ConfigService } from "@nestjs/config";
// 静态
import { join } from "path";
import { NestExpressApplication } from "@nestjs/platform-express";
// 全局验证器
import { ValidationPipe } from "@nestjs/common";
// 全局过滤器
import { HttpExceptionsFilter } from "src/common/filters/http-exceptions-filter";
async function bootstrap() {
const app =
(await NestFactory.create) <
NestExpressApplication >
(AppModule,
{
cors: true, // 开启跨域访问
});
// 限制请求频率
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 1000, // 限制15分钟内最多只能访问1000次
})
);
// 获取配置文件
const config = app.get(ConfigService);
console.log(config);
// 设置 api 访问前缀
const prefix = config.get < string > "app.prefix" || "";
app.setGlobalPrefix(prefix);
// 设置静态资源路径
const rootPath = process.cwd();
const baseDirPath = join(rootPath, config.get("app.file.location") || "");
console.log(baseDirPath);
app.useStaticAssets(baseDirPath, {
prefix: "/profile/", // 虚拟路径
maxAge: 86400000 * 365, // 过期时间 我设置成1年
});
// 开启全局管道
// transform:true 自动将传入的数据转换为相应的DTO(数据传输对象)类型。
// whitelist:true 过滤掉DTO中没有声明的属性。
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
// 开启全局过滤器
app.useGlobalFilters(new HttpExceptionsFilter());
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
调用
这个时候访问不存在得资源得话他就会返回
json
{
"code": 404,
"msg": "资源不存在",
"data": null
}