UNPKG

vue-admin-core

Version:
107 lines (104 loc) 3.21 kB
import { setCache, getCache } from '../../__utils__/cache.mjs'; import { getCachePromise, setCachePromise } from '../../__utils__/cachePromise.mjs'; import { trigger, subscribe } from '../../__utils__/cacheSubscribe.mjs'; import { toValue, onUnmounted } from 'vue'; const useCachePlugin = (fetchInstance, { cacheKey, cacheTime = 5 * 60 * 1e3, staleTime = 0, setCache: customSetCache, getCache: customGetCache }) => { let unSubscribe; let currentPromise; const _setCache = (key, cachedData) => { if (customSetCache) { customSetCache(cachedData); } else { setCache(key, cacheTime, cachedData); } trigger(key, cachedData.data); }; const _getCache = (key, params = []) => { if (customGetCache) { return customGetCache(params); } return getCache(key); }; if (!cacheKey) { return {}; } const cacheData = _getCache(cacheKey); if (cacheData && Object.hasOwnProperty.call(cacheData, "data")) { fetchInstance.data.value = toValue(cacheData.data); fetchInstance.params.value = toValue(cacheData.params); if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData.time <= staleTime) { fetchInstance.loading.value = false; } } unSubscribe = subscribe(cacheKey, (data) => { fetchInstance.data.value = data; }); onUnmounted(() => { unSubscribe == null ? void 0 : unSubscribe(); }); return { onBefore: (params) => { const cacheData2 = _getCache(cacheKey, params); if (!cacheData2 || !Object.hasOwnProperty.call(cacheData2, "data")) { return {}; } if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData2.time <= staleTime) { return { loading: false, data: cacheData2 == null ? void 0 : cacheData2.data, error: void 0, returnNow: true }; } else { return { data: cacheData2 == null ? void 0 : cacheData2.data, error: void 0 }; } }, onRequest: (service, args) => { let servicePromise = getCachePromise(cacheKey); if (servicePromise && servicePromise !== currentPromise) { return { servicePromise }; } servicePromise = service(...args); currentPromise = servicePromise; setCachePromise(cacheKey, servicePromise); return { servicePromise }; }, onSuccess: (data, params) => { if (cacheKey) { unSubscribe == null ? void 0 : unSubscribe(); _setCache(cacheKey, { data, params, time: (/* @__PURE__ */ new Date()).getTime() }); unSubscribe = subscribe(cacheKey, (d) => { fetchInstance.data.value = d; }); } }, onMutate: (data) => { if (cacheKey) { unSubscribe == null ? void 0 : unSubscribe(); _setCache(cacheKey, { data, params: fetchInstance.params, time: (/* @__PURE__ */ new Date()).getTime() }); unSubscribe = subscribe(cacheKey, (d) => { fetchInstance.data.value = d; }); } } }; }; export { useCachePlugin as default }; //# sourceMappingURL=useCachePlugin.mjs.map