1. 重构项目文件结构,统一文件存放位置与命名规则 2. 配置tsconfig路径别名,替换原有相对路径导入 3. 迁移drama-status枚举到dramas.types统一管理 4. 新增全局配置文件与工具类,补充完整注释与文档 5. 修复所有导入路径与依赖引用问题
36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
/**
|
|
* Response interceptor.
|
|
* @file 统一响应结构拦截器
|
|
* @module interceptor/response.interceptor
|
|
* @author zhxiao1124
|
|
*/
|
|
|
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
|
import { Reflector } from "@nestjs/core";
|
|
import { Request } from "express";
|
|
import { map, Observable } from "rxjs";
|
|
import { SUCCESS_MESSAGE } from "@constants/text.constant";
|
|
import { API_MESSAGE_METADATA } from "@app/decorators/api-message.decorator";
|
|
import { getRequestCost } from "@app/utils/request-context.util";
|
|
|
|
@Injectable()
|
|
export class ResponseInterceptor implements NestInterceptor {
|
|
constructor(private readonly reflector = new Reflector()) {}
|
|
|
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
const request = context.switchToHttp().getRequest<Request & { requestId?: string }>();
|
|
const message = this.reflector.get<string>(API_MESSAGE_METADATA, context.getHandler()) ?? SUCCESS_MESSAGE;
|
|
|
|
return next.handle().pipe(
|
|
map((data) => ({
|
|
code: 0,
|
|
data: data ?? {},
|
|
message,
|
|
timestamp: Date.now(),
|
|
requestId: request.requestId,
|
|
cost: `${getRequestCost(request)}ms`,
|
|
})),
|
|
);
|
|
}
|
|
}
|