web.ts 4.06 KB
import type { RequestConfig, ResponseData } from '../../types';
import { parseHeaders } from '../utils';
import type { Adapter } from '../types';
import { BaseAdapter } from './base';
// import qs from "qs"
import { stringify } from '../../libs';
/**
 * Web环境适配器实现
 */
class WebAdapter extends BaseAdapter {
  /**
   * 创建请求选项
   * @param config 请求配置
   * @param fullURL 完整URL
   * @returns 请求选项
   */
  protected createRequestOptions(config: RequestConfig, fullURL: string): RequestInit & { timeout?: number } {
    // 使用基类方法获取基础请求选项
    const baseOptions = this.createBaseRequestOptions(config);
    const { method, headers, data, timeout, signal } = baseOptions;

    // 创建fetch请求选项
    const options: RequestInit & { timeout?: number } = {
      method,
      headers,
      signal,
      timeout
    };

    // 处理请求体
    if (method !== 'GET' && method !== 'HEAD') {
      if (data instanceof FormData || 
          data instanceof URLSearchParams || 
          data instanceof Blob || 
          data instanceof ArrayBuffer) {
        options.body = data;
      } else if (typeof data === 'object' && data !== null) {
        // 检查Content-Type
        const contentType = headers['Content-Type'] || '';
        
        // 如果指定了application/x-www-form-urlencoded,转换为表单数据
        if (contentType.includes('application/x-www-form-urlencoded')) {
          const formData = new URLSearchParams();
          Object.entries(data).forEach(([key, value]) => {
            if (Array.isArray(value)) {
              // 处理数组参数,使用索引格式 key[0]=value, key[1]=value
              value.forEach((item, index) => {
                formData.append(`${key}[${index}]`, String(item));
              });
            } else {
              formData.append(key, String(value));
            }
          });
          options.body = formData;
        } else {
          // 默认使用JSON格式
          options.body = JSON.stringify(data);
          console.log("🚀 ~ WebAdapter ~ createRequestOptions ~ options.body:", options.body)
          // 设置Content-Type为application/json
          if (!headers['Content-Type']) {
            (options.headers as Record<string, string>)['Content-Type'] = 'application/json';
          }
        }
      } else if (data !== undefined) {
        options.body = String(data);
      }
    }

    return options;
  }

  /**
   * 执行请求
   * @param config 请求配置
   * @param options 请求选项
   * @returns Promise<Response>
   */
  protected executeRequest(config: RequestConfig, options: RequestInit & { fullURL: string }): Promise<Response> {
    const { fullURL, ...fetchOptions } = options;
    return fetch(fullURL, fetchOptions);
  }

  /**
   * 转换响应
   * @param response 原始响应
   * @param config 请求配置
   * @returns Promise<ResponseData<any>>
   */
  protected async transformResponse(response: Response, config: RequestConfig): Promise<ResponseData<any>> {
    // 解析响应头
    const headers = parseHeaders(response.headers);
    
    // 解析响应数据
    let data;
    try {
      // 根据响应类型处理数据
      const responseType = config.responseType || 'json';
      switch (responseType) {
        case 'json':
          data = await response.json();
          break;
        case 'text':
          data = await response.text();
          break;
        case 'blob':
          data = await response.blob();
          break;
        case 'arraybuffer':
          data = await response.arrayBuffer();
          break;
        default:
          data = await response.json();
      }
    } catch (e) {
      // 如果解析失败,返回原始文本
      data = await response.text();
    }

    return {
      data,
      status: response.status,
      statusText: response.statusText,
      headers,
      config
    };
  }
}

// 创建适配器实例
const webAdapterInstance = new WebAdapter();

// 导出适配器函数
const webAdapter: Adapter = webAdapterInstance.createAdapter();

export default webAdapter;