Files
ChowBox/miniapp/utils/api.js
王鹏 802b4ba229 fix: 修复 VoiceController Map.of 兼容性 + ExploreController 参数不匹配
- VoiceController: Map.of() -> Collections.singletonMap() 兼容 Java 8
- ExploreController: 补齐 takeoutService.roll() 缺失的 taste/priceRange/allergies 参数

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-08 20:02:27 +08:00

89 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
};