1. 重构项目文件结构,统一文件存放位置与命名规则 2. 配置tsconfig路径别名,替换原有相对路径导入 3. 迁移drama-status枚举到dramas.types统一管理 4. 新增全局配置文件与工具类,补充完整注释与文档 5. 修复所有导入路径与依赖引用问题
52 lines
2.0 KiB
TypeScript
52 lines
2.0 KiB
TypeScript
/**
|
|
* Logger interceptor.
|
|
* @file 请求日志拦截器
|
|
* @module interceptor/logger.interceptor
|
|
* @author zhxiao1124
|
|
*/
|
|
|
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
|
import { Reflector } from "@nestjs/core";
|
|
import { Request, Response } from "express";
|
|
import { Observable, tap } from "rxjs";
|
|
import { API_MESSAGE_METADATA } from "@app/decorators/api-message.decorator";
|
|
import { SUCCESS_MESSAGE } from "@constants/text.constant";
|
|
import { getRequestCost } from "@app/utils/request-context.util";
|
|
import { LogsService } from "@src/logs/logs.service";
|
|
|
|
@Injectable()
|
|
export class LoggerInterceptor implements NestInterceptor {
|
|
constructor(
|
|
private readonly logsService: LogsService,
|
|
private readonly reflector: Reflector,
|
|
) {}
|
|
|
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
const http = context.switchToHttp();
|
|
const request = http.getRequest<Request & { requestId?: string; adminId?: number; user?: { id: number } }>();
|
|
const response = http.getResponse<Response>();
|
|
const message = this.reflector.get<string>(API_MESSAGE_METADATA, context.getHandler()) ?? SUCCESS_MESSAGE;
|
|
|
|
return next.handle().pipe(
|
|
tap(() => {
|
|
this.logsService.recordRequest({
|
|
requestId: request.requestId ?? "",
|
|
method: request.method,
|
|
path: request.originalUrl ?? request.url,
|
|
query: request.query,
|
|
body: request.body,
|
|
statusCode: response.statusCode,
|
|
responseCode: 0,
|
|
message,
|
|
costMs: getRequestCost(request),
|
|
userId: request.user?.id,
|
|
adminId: request.adminId,
|
|
ip: request.ip,
|
|
userAgent: request.get("user-agent"),
|
|
errorStack: undefined,
|
|
});
|
|
}),
|
|
);
|
|
}
|
|
}
|