interceptor.ts
1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { InterceptorHandler, RequestError } from './types';
class InterceptorManager<T = any> {
private handlers: (InterceptorHandler<T> | null)[] = [];
/**
* 添加拦截器
* @param {Function} fulfilled 成功回调
* @param {Function} rejected 失败回调
* @returns {Function} 移除拦截器的函数
*/
use(
fulfilled: (value: T) => T | Promise<T>,
rejected?: (error: RequestError) => any
): number {
const id = this.handlers.push({
fulfilled,
rejected: rejected || ((error: any) => Promise.reject(error))
}) - 1;
// 返回拦截器ID
return id;
}
/**
* 遍历执行拦截器
* @param {Function} fn 执行函数
*/
forEach(fn: (handler: InterceptorHandler<T>) => void): void {
this.handlers.forEach(handler => {
if (handler !== null) {
fn(handler);
}
});
}
/**
* 移除拦截器
* @param {Number} id 拦截器ID
*/
eject(id: number): void {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
}
export default InterceptorManager;