const BASE_URL = 'http://192.168.43.89:8084/api' // 缓存相关常量 const CACHE_PREFIX = 'API_CACHE_' const CACHE_EXPIRE_TIME = 5 * 60 * 1000 // 默认缓存时间5分钟 /** * 获取缓存数据 * @param {string} key - 缓存键名 * @returns {any} 缓存数据(过期返回null) */ export const getCache = (key) => { try { const cacheData = uni.getStorageSync(CACHE_PREFIX + key) if (cacheData && cacheData.expireTime && Date.now() < cacheData.expireTime) { return cacheData.data } // 缓存过期,清除 uni.removeStorageSync(CACHE_PREFIX + key) return null } catch (e) { console.error('获取缓存失败:', e) return null } } /** * 设置缓存数据 * @param {string} key - 缓存键名 * @param {any} data - 要缓存的数据 * @param {number} expireTime - 过期时间(毫秒),默认5分钟 */ export const setCache = (key, data, expireTime = CACHE_EXPIRE_TIME) => { try { const cacheData = { data: data, expireTime: Date.now() + expireTime } uni.setStorageSync(CACHE_PREFIX + key, cacheData) } catch (e) { console.error('设置缓存失败:', e) } } /** * 清除指定缓存 * @param {string} key - 缓存键名 */ export const clearCache = (key) => { try { uni.removeStorageSync(CACHE_PREFIX + key) } catch (e) { console.error('清除缓存失败:', e) } } /** * 清除所有API缓存 */ export const clearAllCache = () => { try { const keys = uni.getStorageInfoSync().keys || [] for (const key of keys) { if (key.startsWith(CACHE_PREFIX)) { uni.removeStorageSync(key) } } } catch (e) { console.error('清除所有缓存失败:', e) } } /** * 获取token * @returns {string|null} token */ export const getToken = () => { try { return uni.getStorageSync('token') || null } catch (e) { console.error('获取token失败:', e) return null } } /** * 设置token * @param {string} token - token值 */ export const setToken = (token) => { try { uni.setStorageSync('token', token) } catch (e) { console.error('设置token失败:', e) } } /** * 清除token */ export const clearToken = () => { try { uni.removeStorageSync('token') } catch (e) { console.error('清除token失败:', e) } } /** * 生成请求缓存键名 * @param {string} url - 请求URL * @param {object} data - 请求参数 * @param {string} method - 请求方法 * @returns {string} 缓存键名 */ const generateCacheKey = (url, data, method) => { const params = JSON.stringify(data || {}) return `${method}_${url}_${params}` } /** * 通用请求函数 * @param {object} options - 请求配置 * @param {string} options.url - 请求URL * @param {string} [options.method='GET'] - 请求方法 * @param {object} [options.data={}] - 请求参数 * @param {object} [options.header={}] - 请求头 * @param {boolean} [options.cache=false] - 是否启用缓存 * @param {number} [options.cacheTime] - 缓存时间(毫秒) * @param {boolean} [options.needToken=true] - 是否需要token * @returns {Promise} 请求Promise */ export const request = (options) => { return new Promise((resolve, reject) => { const { url, method = 'GET', data = {}, header = {}, cache = false, cacheTime, needToken = true } = options // 生成缓存键名 const cacheKey = cache ? generateCacheKey(url, data, method) : null // 如果启用缓存且存在有效缓存,直接返回缓存数据 if (cache && cacheKey) { const cachedData = getCache(cacheKey) if (cachedData !== null) { console.log(`[API] 命中缓存: ${url}`) resolve(cachedData) return } } // 构建请求头 const requestHeader = { 'Content-Type': 'application/json', ...header } // 如果需要token,自动添加到请求头 if (needToken) { const token = getToken() if (token) { requestHeader['Authorization'] = `Bearer ${token}` } } uni.request({ url: BASE_URL + url, method: method, data: data, header: requestHeader, success: (res) => { if (res.statusCode === 200) { // 如果启用缓存,保存响应数据 if (cache && cacheKey && res.data) { setCache(cacheKey, res.data, cacheTime) } resolve(res.data) } else if (res.statusCode === 401) { // token过期,清除token并提示重新登录 clearToken() uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' }) reject({ code: 401, message: '登录已过期' }) } else { reject({ code: res.statusCode, message: res.data?.message || '请求失败' }) } }, fail: (err) => { console.error(`[API] 请求失败: ${url}`, err) reject({ code: -1, message: '网络请求失败', error: err }) } }) }) } // 工具函数导出 export const requestUtils = { getToken, setToken, clearToken, getCache, setCache, clearCache, clearAllCache } export default request