t-comm
Version:
专业、稳定、纯粹的工具库
86 lines (85 loc) • 3.1 kB
TypeScript
/**
* Cocos Network 子模块 - 公共类型定义
*
* 不依赖 @tencent/pmd-network / pmd-network-v2,完全自持,
* 便于 pmd-api-cocos 独立发布、独立编译。
*/
/** 底层请求参数(传给 doRequest 的入参,经过请求拦截器链处理后) */
export interface IRawRequest {
/** 最终请求 URL(已含 query) */
url: string;
/** HTTP method,默认 POST */
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS';
/** 请求头 */
header?: Record<string, string>;
/** 请求体(通常是业务 reqData) */
reqData?: any;
/** 业务层传入的附加参数(会在拦截器链之间透传) */
extra?: {
withCredentials?: boolean;
headers?: Record<string, string>;
/** decorator 内部用,标记重试次数防死循环 */
__cocosRetried?: boolean;
[k: string]: any;
};
/** 记录原始 url(拦截器可能多次改写,需要这个做幂等重试) */
__cocosOriginUrl?: string;
[k: string]: any;
}
/** 底层响应(doRequest 的返回) */
export interface IRawResponse {
/** HTTP 状态码 */
status: number;
/** 2xx => true */
ok: boolean;
/** 响应 body(已做 JSON parse 尝试) */
data: any;
/** 原始状态文本或 errMsg */
statusText: string;
/** 大小写不敏感取 header */
getHeader: (name: string) => string | null | undefined;
}
/**
* 请求拦截器
* 返回 [shouldAbort, param]
* - shouldAbort=true:中止链路,由上层处理
* - shouldAbort=false:继续下一个拦截器
*/
export interface IRequestInterceptor {
interceptor(param: IRawRequest): [
boolean,
IRawRequest
] | Promise<[boolean, IRawRequest]>;
}
/**
* 响应拦截器
* 入参包含 request + response,方便拦截器做路由判断
*/
export interface IResponseInterceptorParam {
/** 原始请求 */
request: IRawRequest;
/** 底层响应(含 getHeader) */
response: IRawResponse;
/** 业务数据(= response.data,由 GetDataInterceptor 提取出来) */
data?: any;
}
export interface IResponseInterceptor {
interceptor(param: IResponseInterceptorParam): [
boolean,
IResponseInterceptorParam
] | Promise<[boolean, IResponseInterceptorParam]>;
}
/**
* 装饰器:包装整个 request Promise,用于做重试、限流、调度等横切逻辑
* 需要自己决定调用 request() 的时机和次数
*/
export type IDecorator = (request: () => Promise<any>, param: IRawRequest) => Promise<any>;
/** 登录态存储接口(业务方注入,用 wx.getStorageSync 封装即可) */
export interface ICocosLoginInfoStorage {
get: (key: string) => any;
set: (key: string, value: any) => void;
/** 删除指定 key(可选,业务方自定义 storage 未实现时回退到 set(key, null)) */
removeItem?: (key: string) => void;
}
/** 登录态(后台下发的 logininfo 字段,本模块不解释具体字段含义,原样透传) */
export type LoginInfo = Record<string, any>;