request-helpers.ts 4.65 KB
import { RequestError } from "../../utils/error";
import { mergeAbortSignals } from "../../utils/polyfill";
import type { RequestConfig, ResponseData } from "../../types";
import { buildURL } from "../utils";

// 将与请求相关的通用辅助逻辑集中在此,便于基类瘦身与复用

export function handleAbortSignal(
  requestTask: { abort: () => void },
  signal?: AbortSignal
): () => void {
  if (!signal) return () => {};
  if (signal.aborted) {
    requestTask.abort();
    return () => {};
  }
  const abortHandler = () => requestTask.abort();
  signal.addEventListener("abort", abortHandler);
  return () => signal.removeEventListener("abort", abortHandler);
}

export function createBaseRequestOptions(config: RequestConfig) {
  const {
    method = "GET",
    headers = {},
    data = {},
    timeout = 5000,
    signal,
  } = config;

  return {
    method: method.toUpperCase(),
    headers,
    data,
    timeout,
    signal,
  };
}

export function createPlatformRequestOptions(
  config: RequestConfig,
  fullURL: string
) {
  const { method, headers, data, timeout } = createBaseRequestOptions(config);

  return {
    url: fullURL,
    method: method as "GET" | "POST" | "PUT" | "DELETE",
    header: headers,
    timeout,
    data,
  };
}

export function executePlatformRequest(
  config: RequestConfig,
  options: any,
  requester: (options: any) => { abort: () => void }
): Promise<any> {
  return new Promise((resolve, reject) => {
    let cleanup: () => void = () => {};
    const requestTask =
      requester({
        ...options,
        success: (res: any) => {
          cleanup();
          resolve(res);
        },
        fail: (err: any) => {
          cleanup();
          reject(err);
        },
        complete: () => cleanup(),
      }) || ({ abort: () => {} } as { abort: () => void });
    cleanup = handleAbortSignal(requestTask, config.signal);
  });
}

export function createTimeoutRace(
  config: RequestConfig,
  options: any,
  fullURL: string,
  timeout: number,
  sendRequest: (
    config: RequestConfig,
    options: any,
    fullURL: string
  ) => Promise<ResponseData<any>>
): Promise<ResponseData<any>> {
  const controller = mergeAbortSignals(config.signal);
  config.signal = controller.signal;
  if (options && typeof options === "object") {
    (options as any).signal = controller.signal;
  }

  const reqPromise = sendRequest(config, options, fullURL);
  let timer: any;
  const timeoutPromise = new Promise<ResponseData<any>>((_, reject) => {
    timer = setTimeout(() => {
      controller.abort("请求超时,超时时间:" + timeout + "ms");
      reject(RequestError.createTimeoutError(config));
    }, timeout);
  });

  return Promise.race([
    reqPromise.finally(() => clearTimeout(timer)),
    timeoutPromise,
  ]);
}

// 通用的发送请求逻辑,依赖注入具体执行/转换/校验/处理方法
export async function sendRequestGeneric(
  config: RequestConfig,
  options: any,
  fullURL: string,
  deps: {
    executeRequest: (config: RequestConfig, options: any) => Promise<any>;
    transformResponse: (
      rawResponse: any,
      config: RequestConfig
    ) => ResponseData<any> | Promise<ResponseData<any>>;
    checkHttpStatus: (
      responseData: ResponseData<any>,
      config: RequestConfig
    ) => void;
    handleResponse: (
      response: ResponseData<any>,
      config: RequestConfig
    ) => ResponseData<any>;
    handleError: (
      error: any,
      config: RequestConfig,
      signal?: AbortSignal
    ) => never;
  }
): Promise<ResponseData<any>> {
  try {
    const optionsWithURL = { ...options, fullURL };
    const rawResponse = await deps.executeRequest(config, optionsWithURL);
    const responseData = await deps.transformResponse(rawResponse, config);
    deps.checkHttpStatus(responseData, config);
    return deps.handleResponse(responseData, config);
  } catch (error) {
    deps.handleError(error as any, config, config.signal);
  }
}

// 通用的处理请求流程逻辑,负责 URL 构建、选项创建与超时竞争
export function handleRequestGeneric(
  config: RequestConfig,
  deps: {
    createRequestOptions: (config: RequestConfig, fullURL: string) => any;
    sendRequest: (
      config: RequestConfig,
      options: any,
      fullURL: string
    ) => Promise<ResponseData<any>>;
  }
): Promise<ResponseData<any>> {
  const {
    baseURL = "",
    url = "",
    method = "GET",
    params = {},
    timeout = 5000,
  } = config;

  const fullURL = buildURL(baseURL, url, params, method);
  const options = deps.createRequestOptions(config, fullURL);

  if (!timeout) {
    return deps.sendRequest(config, options, fullURL);
  }

  return createTimeoutRace(config, options, fullURL, timeout, deps.sendRequest);
}