Files
xk-doctor-wx/subPackages/sub_workbench/prescription_v2/utils/traditionalTcmLocalCache.js

65 lines
1.8 KiB
JavaScript
Raw 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.
/** 中医术语表本地缓存(与 doctor-reception-wx traditional-chinese-medicine-all 配合) */
/** v2条目含 pinyin_full / pinyin_initials 展示串 */
export const STORAGE_KEY = 'xk_traditional_tcm_v2';
/** 默认 3 天(秒),与后端 TRADITIONAL_TCM_CACHE_TTL_SECONDS 默认一致 */
export const DEFAULT_TTL_MS = 259200 * 1000;
function isPayloadValid(obj) {
return (
obj &&
Array.isArray(obj.diseases) &&
Array.isArray(obj.method) &&
Array.isArray(obj.syndrome)
);
}
/**
* 未过期则返回 { diseases, method, syndrome },否则 null
* @returns {{ diseases: any[], method: any[], syndrome: any[] } | null}
*/
export function loadValid() {
try {
const raw = uni.getStorageSync(STORAGE_KEY);
if (raw == null || raw === '') return null;
const obj = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!obj || typeof obj !== 'object') return null;
const { expiresAt, diseases, method, syndrome } = obj;
if (typeof expiresAt !== 'number' || expiresAt <= Date.now()) return null;
const p = { diseases, method, syndrome };
return isPayloadValid(p) ? p : null;
} catch (e) {
return null;
}
}
/**
* @param {{ diseases: any[], method: any[], syndrome: any[] }} payload
* @param {number} expiresAtMs
* @returns {boolean} 是否成功写入 storage
*/
export function save(payload, expiresAtMs) {
if (!isPayloadValid(payload) || typeof expiresAtMs !== 'number') {
return false;
}
try {
const toStore = {
diseases: payload.diseases,
method: payload.method,
syndrome: payload.syndrome,
expiresAt: expiresAtMs,
};
JSON.stringify(toStore);
uni.setStorageSync(STORAGE_KEY, JSON.stringify(toStore));
return true;
} catch (e) {
console.error('traditionalTcm local save failed', e);
uni.showToast({
title: '本地缓存写入失败,本次仍可使用',
icon: 'none',
});
return false;
}
}