interceptor.ts 1.06 KB
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;