vue-admin-core
Version:
A Component Library for Vue 3
111 lines (106 loc) • 3.33 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var cache = require('../../__utils__/cache.js');
var cachePromise = require('../../__utils__/cachePromise.js');
var cacheSubscribe = require('../../__utils__/cacheSubscribe.js');
var vue = require('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 {
cache.setCache(key, cacheTime, cachedData);
}
cacheSubscribe.trigger(key, cachedData.data);
};
const _getCache = (key, params = []) => {
if (customGetCache) {
return customGetCache(params);
}
return cache.getCache(key);
};
if (!cacheKey) {
return {};
}
const cacheData = _getCache(cacheKey);
if (cacheData && Object.hasOwnProperty.call(cacheData, "data")) {
fetchInstance.data.value = vue.toValue(cacheData.data);
fetchInstance.params.value = vue.toValue(cacheData.params);
if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData.time <= staleTime) {
fetchInstance.loading.value = false;
}
}
unSubscribe = cacheSubscribe.subscribe(cacheKey, (data) => {
fetchInstance.data.value = data;
});
vue.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 = cachePromise.getCachePromise(cacheKey);
if (servicePromise && servicePromise !== currentPromise) {
return { servicePromise };
}
servicePromise = service(...args);
currentPromise = servicePromise;
cachePromise.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 = cacheSubscribe.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 = cacheSubscribe.subscribe(cacheKey, (d) => {
fetchInstance.data.value = d;
});
}
}
};
};
exports.default = useCachePlugin;
//# sourceMappingURL=useCachePlugin.js.map