methods.ts 1.01 KB
import type { RequestConfig } from "./types";

/**
 * 为Request类添加HTTP方法别名
 * @param {Object} instance Request实例
 */
export function addMethodAliases(instance: any): void {
  // 添加别名方法
  (["get", "post", "put", "delete", "patch"] as const).forEach((method) => {
    if (method === "get" || method === "delete") {
      // 对于GET、DELETE方法
      instance[method] = function (this: any,
        url: string,
        config: RequestConfig = { sentryDsn: this.defaults.sentryDsn }
      ) {
        return this.request({
          url,
          method: method.toUpperCase(),
          ...config,
        });
      };
    } else {
      // 对于POST、PUT、PATCH方法
      instance[method] = function (this: any,
        url: string,
        data?: any,
        config: RequestConfig = { sentryDsn: this.defaults.sentryDsn }
      ) {
        return this.request({
          url,
          method: method.toUpperCase(),
          data,
          ...config,
        });
      };
    }
  });
}