http.ts 4.27 KB
/*
 * @Description: 简单的HTTP请求工具,用于内部模块
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2025-01-27
 */

import { detectEnvironment, EnvironmentType } from './index';

/**
 * HTTP响应接口
 */
interface HttpResponse<T = any> {
  data: T;
  statusCode: number;
}

/**
 * 请求策略接口
 */
interface RequestStrategy {
  get(url: string): Promise<any>;
}

/**
 * UniApp请求策略
 */
class UniAppStrategy implements RequestStrategy {
  async get(url: string): Promise<any> {
    if (typeof uni === 'undefined' || !uni.request) {
      throw new Error('UniApp环境不可用');
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url,
        method: 'GET',
        success: (res: HttpResponse) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err: any) => {
          reject(new Error(`请求失败: ${err.errMsg || err.message || '未知错误'}`));
        }
      });
    });
  }
}

/**
 * 微信小程序请求策略
 */
class MiniProgramStrategy implements RequestStrategy {
  async get(url: string): Promise<any> {
    if (typeof wx === 'undefined' || !wx.request) {
      throw new Error('微信小程序环境不可用');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url,
        method: 'GET',
        success: (res: HttpResponse) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err: any) => {
          reject(new Error(`请求失败: ${err.errMsg || err.message || '未知错误'}`));
        }
      });
    });
  }
}

/**
 * Web环境请求策略
 */
class WebStrategy implements RequestStrategy {
  async get(url: string): Promise<any> {
    // 优先使用 fetch
    if (typeof fetch !== 'undefined') {
      return this.fetchRequest(url);
    }
    
    // 备选使用 XMLHttpRequest
    if (typeof XMLHttpRequest !== 'undefined') {
      return this.xhrRequest(url);
    }
    
    throw new Error('当前环境不支持HTTP请求');
  }

  private async fetchRequest(url: string): Promise<any> {
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return await response.json();
    } catch (error) {
      throw new Error(`Fetch请求失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  private xhrRequest(url: string): Promise<any> {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      
      xhr.open('GET', url, true);
      xhr.timeout = 10000; // 10秒超时
      
      xhr.onload = () => {
        if (xhr.status === 200) {
          try {
            const data = JSON.parse(xhr.responseText);
            resolve(data);
          } catch (e) {
            reject(new Error('响应数据解析失败'));
          }
        } else {
          reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText || '请求失败'}`));
        }
      };
      
      xhr.onerror = () => reject(new Error('网络请求失败'));
      xhr.ontimeout = () => reject(new Error('请求超时'));
      
      xhr.send();
    });
  }
}

/**
 * 请求策略工厂
 */
class RequestStrategyFactory {
  private static strategies = new Map<EnvironmentType, RequestStrategy>([
    [EnvironmentType.UNIAPP, new UniAppStrategy()],
    [EnvironmentType.MINIPROGRAM, new MiniProgramStrategy()],
    [EnvironmentType.WEB, new WebStrategy()]
  ]);

  static getStrategy(env: EnvironmentType): RequestStrategy {
    const strategy = this.strategies.get(env);
    if (!strategy) {
      throw new Error(`不支持的环境类型: ${env}`);
    }
    return strategy;
  }
}

/**
 * 简单的HTTP GET请求函数,支持微信小程序、Web端和uniapp
 * @param url 请求URL
 * @returns Promise<any> 响应数据
 */
export async function simpleGet(url: string): Promise<any> {
  if (!url || typeof url !== 'string') {
    throw new Error('URL参数无效');
  }

  const env = detectEnvironment();
  const strategy = RequestStrategyFactory.getStrategy(env);
  
  return strategy.get(url);
}