@cloudcome/utils-vue
Version:
cloudcome utils for vue
66 lines (65 loc) • 2.08 kB
JavaScript
import { MemoryCache } from "@cloudcome/utils-core/cache";
import { isObject, isFunction } from "@cloudcome/utils-core/type";
import { ref, computed } from "vue";
import { useAsync } from "./async.mjs";
const defaultCacheStorage = new MemoryCache();
const defaultShareStorage = new MemoryCache();
function useRequest(fn, options) {
const { id, cache, share, onCacheHit, onSuccess } = options || {};
const shareStorage = defaultShareStorage;
const shareAble = isObject(share) ? !share.disabled : share;
const shareOptions = isObject(share) ? share : {};
const hitShare = ref(false);
const _cached = defaultCacheStorage;
const cacheStorage = isObject(cache) ? cache.storage || _cached : _cached;
const cacheAble = isObject(cache) ? !cache.disabled : cache;
const cacheOptions = isObject(cache) ? cache : {};
const hitCache = ref(false);
const cacheableFn = async (...inputs) => {
const requestId = 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 } = useAsync(cacheableFn, options);
const state = computed(() => ({
...asyncState.value,
hitShare: hitShare.value,
hitCache: hitCache.value
}));
return {
...async,
state,
send,
sendAsync,
hitShare,
hitCache
};
}
export {
useRequest
};
//# sourceMappingURL=request.mjs.map