Commit 006694ce by liimin

feat(utils): 添加 AbortController polyfill 和简单 HTTP 工具

为支持小程序环境添加 AbortController polyfill 实现,并创建跨平台的简单 HTTP 请求工具
1 parent 6cb890e9
......@@ -20,6 +20,7 @@ import Trace from "../monitoring/traces";
import Defaults from "./defaults";
import { initSentry, reportNetworkError } from "../monitoring/sentry";
import { buildURL } from "../adapter/utils";
import { createAbortController } from "../utils/polyfill";
interface Interceptors {
request: InterceptorManager<RequestConfig>;
......@@ -89,7 +90,7 @@ class Request {
const config = this.defaults.merge(options);
// 创建AbortController用于请求取消
const controller = new AbortController();
const controller = createAbortController();
// 如果配置中已存在signal,则需要合并处理
if (config.signal) {
......
import Request from './core/request';
import Defaults from './core/defaults';
import * as Sentry from './monitoring/sentry';
import { initAbortControllerPolyfill } from './utils/polyfill';
// 初始化 AbortController polyfill(如果需要的话)
initAbortControllerPolyfill();
export default Request;
export { Defaults, Sentry };
......
......@@ -4,10 +4,12 @@
* @Author: limin
* @Date: 2025-09-09 09:49:02
* @LastEditors: limin
* @LastEditTime: 2025-09-16 08:53:38
* @FilePath: \glsk-fetch\src\traces.ts
* @LastEditTime: 2025-09-18 00:12:50
* @FilePath: \glsk-fetch\src\monitoring\traces.ts
*/
import { simpleGet } from '../utils/http';
/**
* 配置选项接口
*/
......@@ -90,8 +92,7 @@ export class TraceManager {
/**
* 执行带重试的请求
* @returns URL列表
* 获取配置数据(带重试机制)
* @private
*/
private async _fetchWithRetry(): Promise<string[]> {
......@@ -99,13 +100,7 @@ export class TraceManager {
for (let attempt = 0; attempt < this.config.retryCount; attempt++) {
try {
const response = await fetch(this.config.url);
if (!response.ok) {
throw new Error(`请求失败: ${response.status}`);
}
const result = await response.json() as ConfigResponse;
const result = await simpleGet(this.config.url) as ConfigResponse;
const urls = result[this.config.urlField] || [];
return this._processUrls(urls);
} catch (error) {
......
/*
* @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);
}
\ No newline at end of file
/**
* AbortController polyfill for miniprogram environment
* 小程序环境下的 AbortController polyfill
*/
// 简单的事件监听器管理
interface EventListener {
type: string;
listener: Function;
}
// 简单的 AbortSignal 实现(不依赖 EventTarget)
class AbortSignalPolyfill {
public aborted: boolean = false;
public reason: any = undefined;
private listeners: EventListener[] = [];
constructor() {}
addEventListener(type: string, listener: Function): void {
this.listeners.push({ type, listener });
}
removeEventListener(type: string, listener: Function): void {
this.listeners = this.listeners.filter(
l => !(l.type === type && l.listener === listener)
);
}
dispatchEvent(event: { type: string }): void {
this.listeners
.filter(l => l.type === event.type)
.forEach(l => {
try {
l.listener(event);
} catch (error) {
console.warn('Error in event listener:', error);
}
});
}
throwIfAborted(): void {
if (this.aborted) {
throw this.reason || new Error('AbortError');
}
}
}
// 简单的 AbortController 实现
class AbortControllerPolyfill {
public signal: AbortSignalPolyfill;
constructor() {
this.signal = new AbortSignalPolyfill();
}
abort(reason?: any): void {
if (this.signal.aborted) {
return;
}
this.signal.aborted = true;
this.signal.reason = reason;
// 触发 abort 事件
this.signal.dispatchEvent({ type: 'abort' });
}
}
/**
* 初始化 AbortController polyfill
* 只在不支持的环境下添加 polyfill
*/
export function initAbortControllerPolyfill(): void {
// 检查是否已经存在 AbortController
if (typeof globalThis !== 'undefined') {
if (!globalThis.AbortController) {
globalThis.AbortController = AbortControllerPolyfill as any;
globalThis.AbortSignal = AbortSignalPolyfill as any;
}
} else if (typeof global !== 'undefined') {
if (!(global as any).AbortController) {
(global as any).AbortController = AbortControllerPolyfill;
(global as any).AbortSignal = AbortSignalPolyfill;
}
} else if (typeof window !== 'undefined') {
if (!(window as any).AbortController) {
(window as any).AbortController = AbortControllerPolyfill;
(window as any).AbortSignal = AbortSignalPolyfill;
}
}
}
/**
* 检查当前环境是否支持 AbortController
*/
export function isAbortControllerSupported(): boolean {
try {
return typeof AbortController !== 'undefined';
} catch {
return false;
}
}
/**
* 安全地创建 AbortController 实例
* 如果环境不支持,则返回 polyfill 实例
*/
export function createAbortController(): AbortController {
if (isAbortControllerSupported()) {
return new AbortController();
}
// 确保 polyfill 已初始化
initAbortControllerPolyfill();
return new AbortController();
}
\ No newline at end of file
import { RequestConfig, ResponseData } from "../types";
import { RequestError } from "./error";
import { createAbortController } from "./polyfill";
/**
* 判断错误是否可重试
......@@ -51,7 +52,7 @@ export function sendRequestWithRetry(
return delayPromise.then(() => {
// 如果需要重置超时,则重新创建一个新的AbortController
if (config.shouldResetTimeout && config.timeout) {
const controller = new AbortController();
const controller = createAbortController();
config.signal = controller.signal;
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!