UNPKG

vue-hooks-plus

Version:
113 lines (112 loc) 3.39 kB
import { ref, watchEffect, onScopeDispose } from "vue"; import * as cache from "../utils/cache"; import * as cachePromise from "../utils/cachePromise"; import * as cacheSubscribe from "../utils/cacheSubscribe"; const useCachePlugin = (fetchInstance, { cacheKey, cacheTime = 5 * 60 * 1e3, staleTime = 0, setCache: customSetCache, getCache: customGetCache }) => { const unSubscribeRef = ref(); const currentPromiseRef = ref(); const _setCache = (key, cachedData) => { if (customSetCache) { customSetCache(cachedData); } else { cache.setCache(key, cacheTime, cachedData); } cacheSubscribe.trigger(key, cachedData.data); }; const _getCache = (key, params = []) => { if (customGetCache) { return customGetCache(params); } return cache.getCache(key); }; watchEffect(() => { if (!cacheKey) { return; } const cacheData = _getCache(cacheKey); if (cacheData && Object.hasOwnProperty.call(cacheData, "data")) { fetchInstance.state.data = cacheData.data; fetchInstance.state.params = cacheData.params; if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) { fetchInstance.state.loading = false; } } unSubscribeRef.value = cacheSubscribe.subscribe(cacheKey, (data) => { fetchInstance.setState({ data }); }); }); onScopeDispose(() => { var _a; (_a = unSubscribeRef.value) == null ? void 0 : _a.call(unSubscribeRef); }); if (!cacheKey) { return {}; } return { name: "cachePlugin", onBefore: (params) => { const cacheData = _getCache(cacheKey, params); if (!cacheData || !Object.hasOwnProperty.call(cacheData, "data")) { return {}; } if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) { return { loading: false, data: cacheData == null ? void 0 : cacheData.data, returnNow: true }; } else { return { data: cacheData == null ? void 0 : cacheData.data }; } }, onRequest: (service, args) => { let servicePromise = cachePromise.getCachePromise(cacheKey); if (servicePromise && servicePromise !== currentPromiseRef.value) { return { servicePromise }; } servicePromise = service(...args); currentPromiseRef.value = servicePromise; cachePromise.setCachePromise(cacheKey, servicePromise); return { servicePromise }; }, onSuccess: (data, params) => { var _a; if (cacheKey) { (_a = unSubscribeRef.value) == null ? void 0 : _a.call(unSubscribeRef); _setCache(cacheKey, { data, params, time: new Date().getTime() }); unSubscribeRef.value = cacheSubscribe.subscribe(cacheKey, (d) => { fetchInstance.setState({ data: d }); }); } }, onMutate: (data) => { var _a; if (cacheKey) { (_a = unSubscribeRef.value) == null ? void 0 : _a.call(unSubscribeRef); _setCache(cacheKey, { data, params: fetchInstance.state.params, time: new Date().getTime() }); unSubscribeRef.value = cacheSubscribe.subscribe(cacheKey, (d) => { fetchInstance.setState({ data: d }); }); } } }; }; export { useCachePlugin as default };