Featured image of post Nestjs 简易入门(二)请求拦截与异常过滤器与接口文档

Nestjs 简易入门(二)请求拦截与异常过滤器与接口文档

本文含有: Nestjs 创建请求拦截interceptor, 异常过滤器http-exception, 接口文档@nestjs/swagger, 接口文档的API注解

请求拦截

nest g interceptor core/interceptor/transform
  • 1)创建拦截
// src/core/interceptor/transform.interceptor.ts

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from "@nestjs/common";
import { map, Observable } from "rxjs";

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((res) => {
        return {
          statusCode: res.statusCode,
          message: res.message,
          data: res.data,
        };
      })
    );
  }
}
  • 2)在main.ts中全局注册:
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { TransformInterceptor } from "./core/interceptor/transform.interceptor";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 请求拦截
  app.useGlobalInterceptors(new TransformInterceptor());

  await app.listen(3005);
}
bootstrap();

异常过滤器

  • 异常过滤器可以使用以下异常
    • BadRequestException
    • UnauthorizedException
    • NotFoundException
    • ForbiddenException
    • NotAcceptableException
    • RequestTimeoutException
    • ConflictException
    • GoneException
    • PayloadTooLargeException
    • UnsupportedMediaTypeException
    • UnprocessableException
    • InternalServerErrorException
    • NotImplementedException
    • BadGatewayException
    • ServiceUnavailableException
    • GatewayTimeoutException
nest g filter core/filter/http-exception
  • 1)创建拦截
// src/filter/http-exception.filter.ts

import { ExceptionFilter, Catch, ArgumentsHost } from "@nestjs/common";
import { HttpException } from "@nestjs/common";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取请求上下文
    const response = ctx.getResponse(); // 在请求上下文中获取 response 对象
    const request = ctx.getRequest(); // 在请求上下文中获取 request 对象
    const status = exception.getStatus(); // 获取异常的状态码

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}
  • 2)全局注册
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { HttpExceptionFilter } from "./core/filter/http-exception.filter";
import { TransformInterceptor } from "./core/interceptor/transform.interceptor";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 请求拦截
  app.useGlobalInterceptors(new TransformInterceptor());
  // 异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(3005);
}
bootstrap();

接口文档

pnpm install @nestjs/swagger swagger-ui-express -S
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle("管理后台")
    .setDescription("管理后台接口文档")
    .setVersion("1.0")
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("docs", app, document);

  await app.listen(3000);
}
bootstrap();

标签

  • 分类标签
@ApiTags("文章")
@Controller('cats')
export class CatsController {...}

说明

  • 对每个接口有一段描述
  @ApiOperation({ summary: '创建文章' })
  @Post()

传参

// dto/create-cats.dto.ts
export class CreatePostDto {
  @ApiProperty({ description: "文章标题" })
  readonly title: string;
  readonly author: string;
  readonly content: string;
  readonly cover_url: string;
  readonly type: number;
}
//  posts.controller.ts
...
import { CreatePostDto } from './dto/create-post.dto';

@ApiOperation({ summary: '创建文章' })
@Post()
async create(@Body() post:CreatePostDto) {...}
Licensed under CC BY-NC-SA 4.0
本博客已稳定运行
发表了53篇文章 · 总计28.17k字
使用 Hugo 构建
主题 StackJimmy 设计