拦截器

40 阅读1分钟

拦截器

接口返回

// 接口返回信息

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

@Injectable()
export class FormatResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const response = context.switchToHttp().getResponse<FastifyReply>();

    return next.handle().pipe(map((data) => {
      return {
        code: response.statusCode,
        message: 'success',
        data
      }
    }));
  }
}

访问记录

// 接口访问记录
import { CallHandler, ExecutionContext, Inject, Injectable, Logger, NestInterceptor } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { FastifyReply, FastifyRequest } from 'fastify';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Observable, tap } from 'rxjs';

@Injectable()
export class InvokeRecordInterceptor implements NestInterceptor {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
    private readonly jwtService: JwtService,
  ) { }
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest<FastifyRequest>();
    const response = context.switchToHttp().getResponse<FastifyReply>();

    const userAgent = request.headers['user-agent'];

    const { ip, method, url } = request;

    this.logger.debug(
      `${method} ${url} ${ip} ${userAgent}: ${context.getClass().name} ${context.getHandler().name} invoked...`,
    );

    const authorization = request.headers.authorization;
    if (authorization) {
      const verityUser = this.jwtService.verify(authorization);
      this.logger.debug(`user: ${verityUser?.userId}, ${verityUser?.username}`);
    }

    const now = Date.now();

    return next.handle().pipe(
      tap((res) => {
        this.logger.debug(
          `${method} ${url} ${ip} ${userAgent}: ${response.statusCode}: ${Date.now() - now}ms`,
        );
        // this.logger.debug(`Response: ${JSON.stringify(res)}`);
      }),
    );
  }
}

注册

// app.module.ts

{
  provide: APP_INTERCEPTOR,
  useClass: FormatResponseInterceptor
},
{
  provide: APP_INTERCEPTOR,
  useClass: InvokeRecordInterceptor
},