web-helpers.ts 3.11 KB

import { RequestConfig, ResponseData } from "../../types";
import { parseHeaders } from "../utils";
import { createBaseRequestOptions } from "./request-helpers";
// Web: 基于基础选项构造 fetch 的 RequestInit
export function createWebRequestOptions(
  config: RequestConfig,
  fullURL: string
): RequestInit & { timeout?: number; fullURL?: string } {
  const baseOptions = createBaseRequestOptions(config) as {
    method: string;
    headers: Record<string, string>;
    data: any;
    timeout?: number;
    signal?: AbortSignal;
  };
  const { method, headers, data, timeout, signal } = baseOptions;

  const options: RequestInit & { timeout?: number; fullURL?: string } = {
    method,
    headers,
    signal,
    timeout,
    fullURL,
  } as any;

  if (method !== 'GET' && method !== 'HEAD') {
    if (
      (typeof FormData !== 'undefined' && data instanceof FormData) ||
      (typeof URLSearchParams !== 'undefined' && data instanceof URLSearchParams) ||
      (typeof Blob !== 'undefined' && data instanceof Blob) ||
      (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)
    ) {
      (options as any).body = data;
    } else if (typeof data === 'object' && data !== null) {
      const contentType = headers['Content-Type'] || headers['content-type'] || '';
      if (contentType.includes('application/x-www-form-urlencoded')) {
        const formData = new URLSearchParams();
        Object.entries(data).forEach(([key, value]) => {
          if (Array.isArray(value)) {
            value.forEach((item, index) => {
              formData.append(`${key}[${index}]`, String(item));
            });
          } else {
            formData.append(key, String(value));
          }
        });
        (options as any).body = formData;
      } else {
        (options as any).body = JSON.stringify(data);
        if (!headers['Content-Type'] && !headers['content-type']) {
          (options.headers as Record<string, string>)['Content-Type'] = 'application/json';
        }
      }
    } else if (data !== undefined) {
      (options as any).body = String(data);
    }
  }

  return options;
}

// Web 环境:将 fetch Response 转为标准 ResponseData,并根据 responseType 解析 body
export async function transformFetchResponse(
  response: Response,
  config: RequestConfig
): Promise<ResponseData<any>> {
  const headers = parseHeaders((response as any).headers);

  let data: any;
  try {
    const responseType = config.responseType || 'json';
    switch (responseType) {
      case 'json':
        data = await (response as any).json();
        break;
      case 'text':
        data = await (response as any).text();
        break;
      case 'blob':
        data = await (response as any).blob();
        break;
      case 'arraybuffer':
        data = await (response as any).arrayBuffer();
        break;
      default:
        data = await (response as any).json();
    }
  } catch (_e) {
    try {
      data = await (response as any).text();
    } catch {
      data = null;
    }
  }

  return {
    data,
    status: (response as any).status,
    statusText: (response as any).statusText,
    headers,
    config,
  };
}