tmp
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
// utils/store.js
|
||||
// 轻量全局缓存(内存级,冷启动自然为空)
|
||||
// - cacheProfile / getProfile / removeProfile:健康档案缓存(id → 原始文档)
|
||||
// - notifyProfileChange:档案变更通知,列表页订阅后刷新
|
||||
// 注意:拉取列表回填缓存时务必用 cacheProfile(静默),
|
||||
// 只有真实的增删改才走 notifyProfileChange,避免"回填→通知→再拉取"死循环
|
||||
const cache = {}
|
||||
const listeners = {}
|
||||
|
||||
/**
|
||||
* 订阅事件,返回取消订阅函数
|
||||
*/
|
||||
function on(event, cb) {
|
||||
if (!listeners[event]) listeners[event] = []
|
||||
listeners[event].push(cb)
|
||||
return () => off(event, cb)
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
*/
|
||||
function off(event, cb) {
|
||||
const list = listeners[event]
|
||||
if (!list) return
|
||||
const idx = list.indexOf(cb)
|
||||
if (idx > -1) list.splice(idx, 1)
|
||||
}
|
||||
|
||||
function emit(event, data) {
|
||||
;(listeners[event] || []).slice().forEach(cb => {
|
||||
try {
|
||||
cb(data)
|
||||
} catch (err) {
|
||||
console.error(`[store] ${event} 订阅回调异常`, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---- 通用键值 ----
|
||||
|
||||
function get(key) {
|
||||
return cache[key]
|
||||
}
|
||||
|
||||
function set(key, value) {
|
||||
cache[key] = value
|
||||
}
|
||||
|
||||
function remove(key) {
|
||||
delete cache[key]
|
||||
}
|
||||
|
||||
// ---- 健康档案缓存 ----
|
||||
|
||||
/**
|
||||
* 静默回填缓存(不触发变更通知)
|
||||
*/
|
||||
function cacheProfile(profile) {
|
||||
if (profile && profile._id) {
|
||||
cache[`profile:${profile._id}`] = profile
|
||||
}
|
||||
}
|
||||
|
||||
function getProfile(id) {
|
||||
return id ? cache[`profile:${id}`] : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存
|
||||
*/
|
||||
function removeProfile(id) {
|
||||
if (id) delete cache[`profile:${id}`]
|
||||
}
|
||||
|
||||
/**
|
||||
* 档案变更通知(增删改成功后调用)
|
||||
* @param {string} action - 'create' | 'update' | 'remove'
|
||||
* @param {string} id - 档案ID
|
||||
*/
|
||||
function notifyProfileChange(action, id) {
|
||||
emit('profile-change', { action, id })
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
on,
|
||||
off,
|
||||
get,
|
||||
set,
|
||||
remove,
|
||||
cacheProfile,
|
||||
getProfile,
|
||||
removeProfile,
|
||||
notifyProfileChange
|
||||
}
|
||||
Reference in New Issue
Block a user