request.ts 8.73 KB
import InterceptorManager from './interceptor';
import { generateSignature, type SignatureOptions } from './signature';
import type { RequestConfig, ResponseData } from './types';

interface Interceptors {
  request: InterceptorManager;
  response: InterceptorManager;
}

interface MiniProgramRequestOptions {
  url: string;
  method: string;
  header?: RequestConfig['headers'];
  timeout?: number;
  data?: any;
  success: (res: any) => void;
  fail: (err: any) => void;
}

interface MiniProgram {
  request: (options: MiniProgramRequestOptions) => void;
}

declare const wx: MiniProgram | undefined;

class Request {
  defaults: RequestConfig;
  interceptors: Interceptors;
  private adapter: (config: RequestConfig) => Promise<any>;

  constructor(config: RequestConfig = {}) {
    this.defaults = {
      baseURL: '',
      timeout: 5000,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      appId: '',
      appSecret: '',
      ...config
    };

    // 创建拦截器实例
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
    
    // 在初始化时确定环境适配器
    this.adapter = (function(that: Request) {
      if (typeof wx !== 'undefined' && wx && 'request' in wx) {
        // 小程序环境
        return that.miniprogramAdapter.bind(that);
      } else {
        // Web环境
        return that.webAdapter.bind(that);
      }
    })(this);
  }

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

    // 创建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(config: RequestConfig): Promise<any> {
    // 添加签名
    const signedConfig = this.addSignature(config);
    
    // 使用预先确定的适配器
    return this.adapter(signedConfig);
  }

  /**
   * 添加签名信息
   * @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 = generateSignature({
      appId,
      appSecret,
      params
    } as SignatureOptions);

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

    return config;
  }

  /**
   * Web环境适配器
   * @param {Object} config 请求配置
   * @returns {Promise}
   */
  webAdapter(config: RequestConfig): Promise<any> {
    const {
      baseURL = '',
      url = '',
      method = 'GET',
      headers = {},
      params = {},
      data = {},
      timeout = 5000,
      signal
    } = config;

    // 构建完整URL
    let fullURL = baseURL + url;
    
    // 处理GET请求参数
    if (method.toUpperCase() === 'GET' && Object.keys(params).length) {
      const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&');
      fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
    }

    // 创建fetch选项
    const fetchOptions: RequestInit & { timeout?: number } = {
      method: method.toUpperCase(),
      headers: headers as HeadersInit,
      timeout
    };

    // 处理请求体
    if (method.toUpperCase() !== 'GET' && Object.keys(data).length) {
      if (headers['Content-Type'] && headers['Content-Type'].includes('application/json')) {
        fetchOptions.body = JSON.stringify(data);
      } else {
        fetchOptions.body = data as BodyInit;
      }
    }

    // 设置signal
    if (signal) {
      fetchOptions.signal = signal;
    }

    // 设置超时
    let timeoutId: NodeJS.Timeout | null = null;
    if (timeout && signal) {
      // 只有当没有被取消时才设置超时
      if (!signal.aborted) {
        timeoutId = setTimeout(() => {
          if (!signal.aborted) {
            const event = new Event('abort');
            signal.dispatchEvent(event);
          }
        }, timeout);
      }
    }

    // 发起请求
    return fetch(fullURL, fetchOptions)
      .then(response => {
        if (timeoutId) clearTimeout(timeoutId);
        return response.json().catch(() => response.text());
      })
      .then(data => ({
        data,
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      }))
      .catch(error => {
        if (timeoutId) clearTimeout(timeoutId);
        // 处理取消请求的情况
        if (error.name === 'AbortError' || (signal && signal.aborted)) {
          throw new Error('请求已被取消');
        }
        throw error;
      });
  }

  /**
   * 小程序环境适配器
   * @param {Object} config 请求配置
   * @returns {Promise}
   */
  miniprogramAdapter(config: RequestConfig): Promise<any> {
    return new Promise((resolve, reject) => {
      const {
        baseURL = '',
        url = '',
        method = 'GET',
        headers = {},
        params = {},
        data = {},
        timeout = 5000
      } = config;

      // 构建完整URL
      let fullURL = baseURL + url;
      
      // 处理GET请求参数
      if (method.toUpperCase() === 'GET' && Object.keys(params).length) {
        const queryString = Object.keys(params)
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&');
        fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
      }

      // 小程序请求选项
      const requestOption: MiniProgramRequestOptions = {
        url: fullURL,
        method: method.toUpperCase(),
        header: headers,
        timeout,
        success: (res) => {
          resolve({
            data: res.data,
            status: res.statusCode,
            statusText: res.errMsg,
            headers: res.header,
            config
          });
        },
        fail: (err) => {
          reject(err);
        }
      };

      // 处理请求体
      if (method.toUpperCase() !== 'GET') {
        requestOption.data = data;
      }

      // 发起请求
      if (typeof wx !== 'undefined' && wx && 'request' in wx) {
        wx.request(requestOption);
      } else {
        reject(new Error('当前环境不支持小程序请求'));
      }
    });
  }
}

// 添加别名方法
(['get', 'post', 'put', 'delete', 'patch'] as const).forEach(method => {
  (Request.prototype as any)[method] = function(url: string, dataOrConfig?: any, config: RequestConfig = {}) {
    let finalConfig = { ...config };
    
    // 根据方法类型处理参数
    if (method === 'get' || method === 'delete') {
      // 对于GET、DELETE方法,第二个参数是config
      if (dataOrConfig) {
        finalConfig = { ...finalConfig, ...dataOrConfig };
      }
    } else {
      // 对于POST、PUT、PATCH方法,第二个参数是data,第三个参数是config
      finalConfig.data = dataOrConfig;
    }
    
    return this.request({
      url,
      method: method.toUpperCase(),
      ...finalConfig
    });
  };
});

export default Request;