@cloudcome/utils-vue
Version:
cloudcome utils for vue
66 lines (65 loc) • 2.23 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const cache = require("@cloudcome/utils-core/cache");
const type = require("@cloudcome/utils-core/type");
const vue = require("vue");
const async = require("./async.cjs");
const defaultCacheStorage = new cache.MemoryCache();
const defaultShareStorage = new cache.MemoryCache();
function useRequest(fn, options) {
const { id, cache: cache2, share, onCacheHit, onSuccess } = options || {};
const shareStorage = defaultShareStorage;
const shareAble = type.isObject(share) ? !share.disabled : share;
const shareOptions = type.isObject(share) ? share : {};
const hitShare = vue.ref(false);
const _cached = defaultCacheStorage;
const cacheStorage = type.isObject(cache2) ? cache2.storage || _cached : _cached;
const cacheAble = type.isObject(cache2) ? !cache2.disabled : cache2;
const cacheOptions = type.isObject(cache2) ? cache2 : {};
const hitCache = vue.ref(false);
const cacheableFn = async (...inputs) => {
const requestId = type.isFunction(id) ? id() : id;
if (requestId && shareAble) {
const shared = shareStorage.get(requestId);
if (shared) {
hitShare.value = true;
return await shared.data;
}
}
if (requestId && cacheAble) {
const cached = await cacheStorage.get(requestId);
if (cached) {
const data2 = cached.data;
hitCache.value = true;
onCacheHit?.(cached);
onSuccess?.(data2, ...inputs);
return data2;
}
}
const promise = fn(...inputs);
if (requestId && shareAble) {
shareStorage.set(requestId, promise, shareOptions);
}
const data = await promise;
if (requestId && cacheAble) {
cacheStorage.set(requestId, data, cacheOptions);
}
return data;
};
const { state: asyncState, run: send, runAsync: sendAsync, ...async$1 } = async.useAsync(cacheableFn, options);
const state = vue.computed(() => ({
...asyncState.value,
hitShare: hitShare.value,
hitCache: hitCache.value
}));
return {
...async$1,
state,
send,
sendAsync,
hitShare,
hitCache
};
}
exports.useRequest = useRequest;
//# sourceMappingURL=request.cjs.map
;