methods.ts 1.58 KB
import type { RequestConfig } from "../types";
/**
 * 为Request类添加HTTP方法别名
 * @param {Object} instance Request实例
 */
export function addMethodAliases(instance: any): void {
  // 策略接口:定义方法创建策略
  interface MethodStrategy {
    createMethod(method: string): Function;
  }
  // 无数据方法策略(GET、DELETE)
  class NoDataMethodStrategy implements MethodStrategy {
    createMethod(method: string): Function {
      const upperMethod = method.toUpperCase();
      return function (this: any, url: string, config: RequestConfig = {}) {
        return this.request({ url, method: upperMethod, ...config });
      };
    }
  }

  // 有数据方法策略(POST、PUT、PATCH)
  class WithDataMethodStrategy implements MethodStrategy {
    createMethod(method: string): Function {
      const upperMethod = method.toUpperCase();
      return function (this: any, url: string, data?: any, config: RequestConfig = {}) {
        return this.request({ url, method: upperMethod, data, ...config });
      };
    }
  }

  // 策略实例
  const noDataStrategy = new NoDataMethodStrategy();
  const withDataStrategy = new WithDataMethodStrategy();

  // 方法与策略的映射
  const methodStrategies = new Map<string, MethodStrategy>([
    ['get', noDataStrategy],
    ['delete', noDataStrategy],
    ['post', withDataStrategy],
    ['put', withDataStrategy],
    ['patch', withDataStrategy]
  ]);

  // 使用策略模式创建方法别名
  methodStrategies.forEach((strategy, methodName) => {
    instance[methodName] = strategy.createMethod(methodName);
  });
}