/** * API 客户端 * 统一封装所有 HTTP 请求 */ import { API_CONFIG, DEBUG_CONFIG } from '../config/index.js'; import { UserCache } from './user-cache.js'; export class ApiClient { /** * 构建查询参数 * @param {Object} params - 参数对象 * @returns {string} - URL 编码的参数字符串 */ static buildParams(params) { return Object.entries(params) .map(([k, v]) => `${k}=${encodeURIComponent(typeof v === 'string' ? v : JSON.stringify(v))}`) .join('&'); } /** * 获取请求头 * @param {string} contentType - 内容类型 * @returns {Object} - 请求头对象 */ static getHeaders(contentType = 'application/json') { const headers = { 'Content-Type': contentType }; // 添加用户会话信息 const session = UserCache.getUserSession(); if (session?.sessionid) { headers['jsessionid'] = session.sessionid; } return headers; } /** * POST 请求 - JSON 格式 * @param {string} endpoint - API 端点 * @param {Object} data - 请求数据 * @returns {Promise} - 响应数据 */ static async post(endpoint, data = {}) { const url = API_CONFIG.BASE_URL + endpoint; const headers = this.getHeaders('application/json'); try { const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(data) }); const result = await response.json(); if (DEBUG_CONFIG.ENABLED && DEBUG_CONFIG.VERBOSE_LOGGING) { console.log(`[API] POST ${endpoint}`, { request: data, response: result }); } return result; } catch (error) { console.error(`[API] POST ${endpoint} 请求失败:`, error); return { retcode: -1, retinfo: error.message || '网络错误,请稍后重试' }; } } /** * XPOST 请求 - x-www-form-urlencoded 格式 * @param {string} endpoint - API 端点 * @param {Object} data - 请求数据(会被包装在 bean 对象中) * @returns {Promise} - 响应数据 */ static async xpost(endpoint, data = {}) { const url = API_CONFIG.BASE_URL + endpoint; const headers = this.getHeaders('application/x-www-form-urlencoded'); try { const response = await fetch(url, { method: 'POST', headers, body: this.buildParams({ bean: data }) }); const result = await response.json(); if (DEBUG_CONFIG.ENABLED && DEBUG_CONFIG.VERBOSE_LOGGING) { console.log(`[API] XPOST ${endpoint}`, { request: data, response: result }); } return result; } catch (error) { console.error(`[API] XPOST ${endpoint} 请求失败:`, error); return { retcode: -1, retinfo: error.message || '网络错误,请稍后重试' }; } } /** * GET 请求 * @param {string} endpoint - API 端点 * @param {Object} params - 查询参数 * @returns {Promise} - 响应数据 */ static async get(endpoint, params = {}) { const url = new URL(API_CONFIG.BASE_URL + endpoint); // 添加查询参数 Object.entries(params).forEach(([key, value]) => { url.searchParams.append(key, value); }); const headers = this.getHeaders('application/json'); try { const response = await fetch(url, { method: 'GET', headers }); const result = await response.json(); if (DEBUG_CONFIG.ENABLED && DEBUG_CONFIG.VERBOSE_LOGGING) { console.log(`[API] GET ${endpoint}`, { params, response: result }); } return result; } catch (error) { console.error(`[API] GET ${endpoint} 请求失败:`, error); return { retcode: -1, retinfo: error.message || '网络错误,请稍后重试' }; } } }