UNPKG

@pisell/pisellos

Version:

一个可扩展的前端模块化SDK框架,支持插件系统

319 lines (317 loc) 8.63 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/plugins/request.ts var request_exports = {}; __export(request_exports, { RequestError: () => RequestError, default: () => request_default }); module.exports = __toCommonJS(request_exports); var RequestError = class extends Error { constructor(message, config, request, response) { super(message); this.name = "RequestError"; this.config = config; this.request = request; this.response = response; } }; var RequestPluginImpl = class { constructor() { this.name = "request"; this.version = "1.0.0"; this.core = null; /** * 默认请求选项 */ this.defaultOptions = { method: "GET", headers: { "Content-Type": "application/json" }, timeout: 3e4, responseType: "json" }; /** * 全局拦截器 */ this.interceptors = { request: [], response: [], error: [] }; } // 初始化方法 initialize() { this.core = globalThis.pisellOS; console.log("[RequestPlugin] 初始化完成"); } // 销毁方法 destroy() { console.log("[RequestPlugin] 已销毁"); } /** * 添加请求拦截器 */ addRequestInterceptor(interceptor) { this.interceptors.request.push(interceptor); } /** * 添加响应拦截器 */ addResponseInterceptor(interceptor) { this.interceptors.response.push(interceptor); } /** * 添加错误拦截器 */ addErrorInterceptor(interceptor) { this.interceptors.error.push(interceptor); } /** * GET 请求 */ get(url, options = {}) { return this.request({ ...options, url, method: "GET" }); } /** * POST 请求 */ post(url, data, options = {}) { return this.request({ ...options, url, method: "POST", data }); } /** * PUT 请求 */ put(url, data, options = {}) { return this.request({ ...options, url, method: "PUT", data }); } /** * DELETE 请求 */ delete(url, options = {}) { return this.request({ ...options, url, method: "DELETE" }); } /** * 通用请求方法 */ async request(options) { let config = { ...this.defaultOptions, ...options, headers: { ...this.defaultOptions.headers, ...options.headers } }; if (!config.headers["authorization"] && this.core) { const windowPlugin = this.core.getPlugin("window"); if (windowPlugin) { config.headers["authorization"] = windowPlugin.localStorage.getItem("token") || ""; } } for (const interceptor of this.interceptors.request) { try { config = await Promise.resolve(interceptor(config)); } catch (error) { const requestError = error instanceof RequestError ? error : new RequestError( error instanceof Error ? error.message : "请求拦截器错误", config ); let processedError = requestError; for (const errorInterceptor of this.interceptors.error) { try { processedError = await Promise.resolve( errorInterceptor(processedError) ); } catch (e) { } } throw processedError; } } try { const response = await this.performRequest(config); let processedResponse = response; for (const interceptor of this.interceptors.response) { try { processedResponse = await Promise.resolve( interceptor(processedResponse) ); } catch (error) { const requestError = error instanceof RequestError ? error : new RequestError( error instanceof Error ? error.message : "响应拦截器错误", config, null, response ); let processedError = requestError; for (const errorInterceptor of this.interceptors.error) { try { processedError = await Promise.resolve( errorInterceptor(processedError) ); } catch (e) { } } throw processedError; } } return processedResponse.data; } catch (error) { const requestError = error instanceof RequestError ? error : new RequestError( error instanceof Error ? error.message : "请求错误", config ); let processedError = requestError; for (const errorInterceptor of this.interceptors.error) { try { processedError = await Promise.resolve( errorInterceptor(processedError) ); } catch (e) { } } throw processedError; } } /** * 执行实际的请求 * 这里实现了一个基于 fetch API 的请求 */ async performRequest(config) { const { url, method, headers, data, params, timeout, responseType, withCredentials } = config; if (!url) { throw new RequestError("URL不能为空", config); } let fullUrl = url; if (params && Object.keys(params).length > 0) { const queryString = Object.entries(params).map( ([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}` ).join("&"); fullUrl += (url.includes("?") ? "&" : "?") + queryString; } const fetchOptions = { method, headers: { ...headers }, credentials: withCredentials ? "include" : "same-origin" }; if (data !== void 0 && method !== "GET" && method !== "HEAD") { if (data instanceof FormData) { fetchOptions.body = data; delete fetchOptions.headers["Content-Type"]; } else if (typeof data === "object") { fetchOptions.body = JSON.stringify(data); } else { fetchOptions.body = data; } } let timeoutId; const timeoutPromise = new Promise((_, reject) => { if (timeout) { timeoutId = setTimeout(() => { reject(new RequestError(`请求超时: ${timeout}ms`, config)); }, timeout); } }); try { const fetchPromise = typeof fetch !== "undefined" ? fetch(fullUrl, fetchOptions) : Promise.reject( new RequestError("当前环境不支持 fetch API", config) ); const response = await Promise.race([fetchPromise, timeoutPromise]); const responseHeaders = {}; response.headers.forEach((value, key) => { responseHeaders[key] = value; }); let responseData; if (responseType === "json") { try { responseData = await response.json(); } catch (e) { responseData = await response.text(); } } else if (responseType === "text") { responseData = await response.text(); } else if (responseType === "arraybuffer") { responseData = await response.arrayBuffer(); } else if (responseType === "blob") { responseData = await response.blob(); } else { try { responseData = await response.json(); } catch (e) { responseData = await response.text(); } } const result = { data: responseData, status: response.status, statusText: response.statusText, headers: responseHeaders, config }; if (!response.ok) { throw new RequestError( `请求失败,状态码: ${response.status}`, config, fetchOptions, result ); } return result; } finally { if (timeoutId) { clearTimeout(timeoutId); } } } }; var request_default = new RequestPluginImpl(); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { RequestError });