request.ts 7.01 KB
import InterceptorManager from './interceptor';
import { generateSignature, type SignatureOptions, type SignatureResult } from './signature';
import type { RequestConfig, ResponseData } from './types';
import { RequestError } from './error';
import { getAdapter, type Adapter } from './adapters';

interface Interceptors {
  request: InterceptorManager<RequestConfig>;
  response: InterceptorManager<ResponseData>;
}

class Request {
  defaults: RequestConfig;
  interceptors: Interceptors;
  private adapter: Adapter;
  private signFunc: (options: SignatureOptions) => SignatureResult;

  constructor(config: RequestConfig = {}) {
    this.defaults = {
      baseURL: '',
      timeout: 5000,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      appId: '',
      appSecret: '',
      // 默认重试配置
      retries: 0,           // 默认不重试
      retryDelay: 300,      // 默认重试延迟300ms
      shouldResetTimeout: true,  // 默认重试时重置超时
      ...config
    };

    // 创建拦截器实例
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
    
    // 在初始化时获取适合当前环境的适配器
    this.adapter = getAdapter();
    
    // 在初始化时确定签名函数
    this.signFunc = (function(config: RequestConfig) {
      // 如果用户提供了自定义签名函数,则使用它,否则使用默认签名函数
      return config.signatureFunc || generateSignature;
    })(this.defaults);
  }

  /**
   * 发起请求
   * @param {Object} options 请求配置
   * @returns {Promise & {abort: Function}} 可取消的请求Promise
   */
  request<T = any>(options: RequestConfig = {}): Promise<ResponseData<T>> & { abort?: () => void } {
    // 合并配置
    const config: RequestConfig = { 
      ...this.defaults, 
      ...options,
      // 确保params正确合并
      params: { ...this.defaults.params, ...options.params }
    };

    // 创建AbortController用于请求取消
    const controller = new AbortController();
    
    // 如果配置中已存在signal,则需要合并处理
    if (config.signal) {
      // 当外部signal触发abort时,也触发内部controller的abort
      config.signal.addEventListener('abort', () => {
        controller.abort();
      });
    }
    
    // 将controller.signal设置到config中
    config.signal = controller.signal;

    // 创建请求链
    const chain: Array<(value: any) => any | Promise<any> | undefined> = [this.dispatchRequest.bind(this), () => undefined];
    
    // 添加请求拦截器
    this.interceptors.request.forEach(interceptor => {
      chain.unshift(interceptor.fulfilled, interceptor.rejected);
    });

    // 添加响应拦截器
    this.interceptors.response.forEach(interceptor => {
      chain.push(interceptor.fulfilled, interceptor.rejected);
    });

    // 执行请求链
    let promise = Promise.resolve(config);

    while (chain.length) {
      promise = promise.then(chain.shift() as (value: any) => any, chain.shift() as (value: any) => any);
    }

    // 为Promise添加abort方法
    const promiseWithAbort = promise as Promise<any> & { abort: () => void };
    promiseWithAbort.abort = () => {
      controller.abort();
    };

    return promiseWithAbort;
  }

  /**
   * 处理请求分发
   * @param {Object} config 请求配置
   * @returns {Promise}
   */
  dispatchRequest<T = any>(config: RequestConfig): Promise<ResponseData<T>> {
    // 添加签名
    const signedConfig = this.addSignature(config);
    
    // 使用预先确定的适配器,并添加重试逻辑
    return this.sendRequestWithRetry(signedConfig, 0) as Promise<ResponseData<T>>;
  }
  
  /**
   * 发送请求并处理重试逻辑
   * @param {RequestConfig} config 请求配置
   * @param {number} retryCount 当前重试次数
   * @returns {Promise}
   */
  private sendRequestWithRetry(config: RequestConfig, retryCount: number): Promise<ResponseData<any>> {
    const { retries = 0, retryDelay = 300, retryCondition } = config;
    
    return this.adapter(config).catch((error: RequestError) => {
      // 判断是否需要重试
      const shouldRetry = (
        // 未超过最大重试次数
        retryCount < retries && 
        // 如果有自定义重试条件,则使用自定义条件判断
        (retryCondition ? retryCondition(error) : this.isRetryableError(error))
      );
      
      if (shouldRetry) {
        console.log(`请求失败,正在进行第${retryCount + 1}次重试...`);
        
        // 创建延迟Promise
        const delayPromise = new Promise(resolve => {
          setTimeout(resolve, retryDelay);
        });
        
        // 延迟后重试
        return delayPromise.then(() => {
          // 如果需要重置超时,则重新创建一个新的AbortController
          if (config.shouldResetTimeout && config.timeout) {
            const controller = new AbortController();
            config.signal = controller.signal;
          }
          
          return this.sendRequestWithRetry(config, retryCount + 1);
        });
      }
      
      // 不需要重试,直接抛出错误
      throw error;
    });
  }
  
  /**
   * 判断错误是否可重试
   * @param {RequestError} error 错误对象
   * @returns {boolean} 是否可重试
   */
  private isRetryableError(error: RequestError): boolean {
    // 网络错误、服务器错误(5xx)可以重试
    // 请求被取消、客户端错误(4xx)不重试
    return (
      error.code === 'NETWORK_ERROR' || 
      (error.response && error.response.status >= 500 && error.response.status < 600)
    );
  }

  /**
   * 添加签名信息
   * @param {Object} config 请求配置
   * @returns {Object} 添加签名后的配置
   */
  addSignature(config: RequestConfig): RequestConfig {
    const { appId, appSecret } = config;
    if (!appId || !appSecret) {
      console.warn('缺少签名所需的应用ID或密钥');
      return config;
    }

    // 获取请求参数
    const params = { ...config.params };

    // 使用预先确定的签名函数
    const signature = this.signFunc({ appId, appSecret, params });

    // 添加签名到请求头
    config.headers = {
      ...config.headers,
      'X-App-Id': appId,
      'X-Nonce': signature.nonce,
      'X-Timestamp': signature.timestamp,
      'X-Sign': signature.sign
    };

    return config;
  }


}

// 添加别名方法
(['get', 'post', 'put', 'delete', 'patch'] as const).forEach(method => {
  if (method === 'get' || method === 'delete') {
    // 对于GET、DELETE方法
    (Request.prototype as any)[method] = function(url: string, config: RequestConfig = {}) {
      return this.request({
        url,
        method: method.toUpperCase(),
        ...config
      });
    };
  } else {
    // 对于POST、PUT、PATCH方法
    (Request.prototype as any)[method] = function(url: string, data?: any, config: RequestConfig = {}) {
      return this.request({
        url,
        method: method.toUpperCase(),
        data,
        ...config
      });
    };
  }
});

export default Request;