UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

85 lines (84 loc) 3.27 kB
import type { IResponseInterceptor, IResponseInterceptorParam } from '../../types'; /** * Aegis 上报专用:响应数据拦截器 * * - 业务:在「响应拦截器链」里加本拦截器,把 request / response / 耗时 一次性上报 * - 必须配合 `AegisStartTimeInterceptor`(请求打点)一起使用,否则 duration 始终为 0 * * 上报字段(透传给业务注入的 report 回调): * - url 请求完整 URL(已拼 baseUrl) * - method HTTP method * - status HTTP 状态码 * - ret 业务返回码 r(已被 NormalizeResponseRetInterceptor 归一化) * - requestBody 请求体(JSON.stringify + 截断) * - responseData 响应 data(JSON.stringify + 截断) * - responseHeader 响应头(完整对象,截断总长) * - duration 耗时 ms * - ok 是否 2xx * - isAbort 是否被业务中断(链中其他拦截器 abort=true) * * 截断策略: * - `truncateSize` 控制单项 JSON 序列化后最大字符数(默认 1000 字符),防 aegis 单条日志过大 * - `truncateSize <= 0` 表示不截断(业务方自己控制) * - 截断发生在「序列化后」用 `slice(0, size) + '...(truncated)'` 标记,不破坏原始 data * * 异常处理: * - 上报回调内部异常被 try/catch 吃掉,不影响主链路 * - aegis.reportEvent 失败不会影响业务响应 * * 位置建议: * - 放在 `NormalizeResponseRetInterceptor` 之后、`GetDataInterceptor` 之前 * - 这样 `r` / `msg` 已被归一化,data 还能继续走 GetData 拆包 */ export interface IAegisReportInfo { /** 完整请求 URL(已拼 baseUrl) */ url: string; /** HTTP method */ method: string; /** HTTP 状态码(2xx / 4xx / 5xx) */ status: number; /** 业务返回码 r(已被归一化) */ ret: number | null; /** 请求体 */ requestBody: Record<string, any>; /** 响应 data */ responseData: Record<string, any>; /** 响应 header */ responseHeader: Record<string, any>; /** 耗时 ms(基于 AegisStartTimeInterceptor 注入的 __aegisStartTime) */ duration: number; /** 是否 2xx */ ok: boolean; /** 是否被其他拦截器 abort(业务错误) */ isAbort: boolean; /** 异常 msg(如果 data.msg 存在) */ msg?: string; } export interface IAegisReportOptions { /** * 业务注入的上报回调(必填)。 * * 形如: * ```ts * aegisReport: (info) => { * aegis.infoAll({ * msg: `${info.method} ${info.url} ret=${info.ret} dur=${info.duration}ms`, * ext1: info.requestBody, * ext2: info.responseData, * ext3: `${info.status} | ${info.responseHeader}`, * duration: info.duration, * }); * } * ``` */ report: (info: IAegisReportInfo) => void; /** * 单项序列化后最大字符数,默认 1000。<=0 不截断。 */ truncateSize?: number; } export declare class AegisReportInterceptor implements IResponseInterceptor { private options; constructor(options: IAegisReportOptions); interceptor(param: IResponseInterceptorParam): [boolean, IResponseInterceptorParam]; }