在main.ts中获取配置文件中的信息(.env/yml)
import { ConfigService } from '@nestjs/config'; // 获取配置文件 const config = app.get(ConfigService);
全局请求前缀
main.ts 中配置
app.setGlobalPrefix(config.get("app.prefix") ?? "api");
验证器配置
1、安装
npm i --save class-validator class-transformer
2、全局配置
app.useGlobalPipes(new ValidationPipe({
whitelist: true, //过滤掉方法处理程序不应该接收的属性
transform: true, //根据其 DTO 类自动将有效负载转换为类型化的对象
}))
安全防护
1、安装
npm i helmet -D
2、全局配置
import helment from 'helmet';
// 安全防护
app.use(helment())
前端返参处理
1、响应映射(新建transform-interceptor.filter.ts)
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { map, Observable } from "rxjs";
export interface Response<T> {
data: T
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<Response<T>> {
return next.handle().pipe(map(data => {
return {
data,
code: 200,
message: '操作成功'
}
}))
}
}
2、编写异常过滤器(http-exception.filter.ts)
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
} from '@nestjs/common';
import { Response } from 'express';
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = (exception instanceof HttpException) ? exception.getStatus() : 500;
response.status(200).json({
data: null,
message: exception.message,
code: status
});
}
}
3、配置全局过滤器
// 配置全局拦截器 -- 响应映射
app.useGlobalInterceptors(new TransformInterceptor())
// 配置异常过滤器 -- 异常处理
app.useGlobalFilters(new HttpExceptionFilter());
swagger配置
1、安装
npm install --save @nestjs/swagger
2、配置
// 配置swagger
const swaggerConfig = new DocumentBuilder()
.setTitle('Nestjs-demo')
.setDescription('Nestjs-demo')
.setVersion('1.0')
.addTag("nest")
.build();
const documentFactiry = () => SwaggerModule.createDocument(app, swaggerConfig);
// swagger访问路径
SwaggerModule.setup('api-docs', app, documentFactiry);