Files
ChowBox/miniapp/utils/api.js

89 lines
2.1 KiB
JavaScript
Raw Normal View History

const app = getApp();
// 客户端缓存key → { data, expireAt }
const CACHE_PREFIX = 'api_cache_';
const DEFAULT_TTL = 30 * 60 * 1000; // 默认 30 分钟
function request(method, path, data) {
return new Promise((resolve, reject) => {
wx.request({
url: app.globalData.baseUrl + path,
method: method,
data: data,
header: { 'Content-Type': 'application/json' },
success: (res) => {
if (res.statusCode === 200 && res.data.code === 200) {
resolve(res.data.data);
} else {
reject(res.data);
}
},
fail: (err) => {
reject(err);
}
});
});
}
/**
* 带客户端缓存的 GET 请求
* @param {string} path 请求路径
* @param {object} data 请求参数
* @param {number} ttlMs 缓存时长(毫秒)默认 30 分钟
*/
function getWithCache(path, data, ttlMs) {
const cacheKey = CACHE_PREFIX + path + '_' + JSON.stringify(data || {});
const ttl = ttlMs || DEFAULT_TTL;
// 读缓存
try {
const cached = wx.getStorageSync(cacheKey);
if (cached && cached.expireAt > Date.now()) {
return Promise.resolve(cached.data);
}
} catch (e) {
// 读取失败,忽略
}
return request('GET', path, data).then((result) => {
// 写缓存
try {
wx.setStorageSync(cacheKey, {
data: result,
expireAt: Date.now() + ttl
});
} catch (e) {
// 写入失败,忽略(存储满了等)
}
return result;
});
}
/**
* 清除过期缓存
*/
function clearExpiredCache() {
try {
const info = wx.getStorageInfoSync();
const keys = info.keys || [];
const now = Date.now();
keys.forEach((key) => {
if (key.startsWith(CACHE_PREFIX)) {
const cached = wx.getStorageSync(key);
if (cached && cached.expireAt < now) {
wx.removeStorageSync(key);
}
}
});
} catch (e) {
// 静默失败
}
}
module.exports = {
get: (path, data) => request('GET', path, data),
post: (path, data) => request('POST', path, data),
getWithCache,
clearExpiredCache
};