nest全局配置项

在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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值