Skip to content

Instantly share code, notes, and snippets.

@abigmiu
Last active June 11, 2025 05:22
Show Gist options
  • Save abigmiu/c9cf9e8493e08cdf4e3b983db5ed3401 to your computer and use it in GitHub Desktop.
Save abigmiu/c9cf9e8493e08cdf4e3b983db5ed3401 to your computer and use it in GitHub Desktop.
uniapp 创建可删除的intercept
// 用于拦截指定API,返回一个移除"添加时"拦截器的函数
type IStopInterceptor = () => void;
interface IInterceptorItem {
id: string;
interceptor: UniApp.InterceptorOptions,
}
class Interceptors {
private interceptors: Record<string, IInterceptorItem[]> = {};
private id = 0;
private initInterceptor(apiName: string) {
if (this.interceptors[apiName]) return;
this.initInterceptor[apiName] = [];
const _this = this;
uni.addInterceptor(apiName, {
invoke(...args) {
_this.interceptors[apiName].forEach((item) => {
if (item.interceptor.invoke) {
item.interceptor.invoke(...args)
}
})
},
success(...args) {
_this.interceptors[apiName].forEach((item) => {
if (item.interceptor.success) {
item.interceptor.success(...args)
}
})
},
fail(...args) {
_this.interceptors[apiName].forEach((item) => {
if (item.interceptor.fail) {
item.interceptor.fail(...args)
}
})
},
complete(...args) {
_this.interceptors[apiName].forEach((item) => {
if (item.interceptor.complete) {
item.interceptor.complete(...args)
}
})
},
returnValue(res) {
_this.interceptors[apiName].forEach((item) => {
if (item.interceptor.returnValue) {
return item.interceptor.returnValue(res)
}
})
}
})
}
/** 添加拦截器 */
addInterceptor(
apiName: string,
interceptorOption: UniApp.InterceptorOptions,
id?: string,
) {
this.initInterceptor(apiName);
if (!id) {
this.id += 1;
id = this.id.toString();
}
this.interceptors[apiName].push({
id,
interceptor: interceptorOption,
})
return () => this.removeInterceptor(apiName, id);
}
/** 移除拦截器 */
removeInterceptor(apiName: string, id: string) {
if (!this.interceptors[apiName]) {
console.warn(`拦截器 ${apiName} 无数据`);
return;
}
const index = this.interceptors[apiName].findIndex((item) => item.id === id);
if (index < 0) {
console.warn(`拦截器 ${apiName}-${id} 不存在`);
return;
}
this.interceptors[apiName].splice(index, 1);
}
}
const interceptors = new Interceptors();
/**
*
* @param apiName
* @param interceptorOption
* @param id
* @returns 移除当前拦截器
*/
export function useUniIntercept(
apiName: string,
interceptorOption: UniApp.InterceptorOptions,
id?: string,
): IStopInterceptor {
return interceptors.addInterceptor(apiName, interceptorOption, id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment