vue-request
Advanced tools
Comparing version 2.0.0-rc.4 to 2.0.0
@@ -27,21 +27,17 @@ 'use strict'; | ||
const isDocumentVisibility = () => { | ||
var _window$document; | ||
if (isServer || isNil((_window$document = window.document) === null || _window$document === void 0 ? void 0 : _window$document.visibilityState)) return true; | ||
if (isServer || isNil(window.document?.visibilityState)) return true; | ||
return window.document.visibilityState === 'visible'; | ||
}; | ||
const isOnline = () => { | ||
var _ref, _window$navigator; | ||
return (_ref = !isServer && ((_window$navigator = window.navigator) === null || _window$navigator === void 0 ? void 0 : _window$navigator.onLine)) !== null && _ref !== void 0 ? _ref : true; | ||
var _ref; | ||
return (_ref = !isServer && window.navigator?.onLine) !== null && _ref !== void 0 ? _ref : true; | ||
}; | ||
const resolvedPromise = () => new Promise(() => {}); | ||
const get = (source, path, defaultValue = undefined) => { | ||
const get = function (source, path) { | ||
let defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; | ||
// a[3].b -> a.3.b | ||
const paths = path.replace(/\[(\d+)\]/g, '.$1').split('.'); | ||
let result = source; | ||
for (const p of paths) { | ||
result = Object(result)[p]; | ||
if (result === undefined) { | ||
@@ -51,3 +47,2 @@ return defaultValue; | ||
} | ||
return result; | ||
@@ -57,12 +52,10 @@ }; | ||
const result = Object.assign({}, object); | ||
for (const key of keys) { | ||
delete result[key]; | ||
} | ||
return result; | ||
} | ||
const warning = (message, throwError = false) => { | ||
const warning = function (message) { | ||
let throwError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; | ||
const msg = `Warning: [vue-request] ${message}`; | ||
if (throwError) { | ||
@@ -93,9 +86,8 @@ return new Error(msg); | ||
const oldCache = CACHE_MAP.get(cacheKey); | ||
if (oldCache !== null && oldCache !== void 0 && oldCache.timer) { | ||
if (oldCache?.timer) { | ||
clearTimeout(oldCache.timer); | ||
} | ||
const timer = setTimeout(() => CACHE_MAP.delete(cacheKey), cacheTime); | ||
CACHE_MAP.set(cacheKey, { ...data, | ||
CACHE_MAP.set(cacheKey, { | ||
...data, | ||
timer | ||
@@ -106,5 +98,3 @@ }); | ||
if (cacheKey) { | ||
var _CACHE_MAP$get; | ||
const timer = (_CACHE_MAP$get = CACHE_MAP.get(cacheKey)) === null || _CACHE_MAP$get === void 0 ? void 0 : _CACHE_MAP$get.timer; | ||
const timer = CACHE_MAP.get(cacheKey)?.timer; | ||
timer && clearTimeout(timer); | ||
@@ -127,3 +117,2 @@ CACHE_MAP.delete(cacheKey); | ||
*/ | ||
function debounce(func, wait, options) { | ||
@@ -134,12 +123,9 @@ let lastArgs, lastThis, maxWait, result, timerId, lastCallTime; | ||
let maxing = false; | ||
let trailing = true; // Bypass `requestAnimationFrame` by explicitly setting `wait=0`. | ||
let trailing = true; | ||
// Bypass `requestAnimationFrame` by explicitly setting `wait=0`. | ||
const useRAF = !wait && wait !== 0 && typeof window.requestAnimationFrame === 'function'; | ||
if (typeof func !== 'function') { | ||
throw new TypeError('Expected a function'); | ||
} | ||
wait = +wait || 0; | ||
if (isObject(options)) { | ||
@@ -151,3 +137,2 @@ leading = !!options.leading; | ||
} | ||
function invokeFunc(time) { | ||
@@ -161,3 +146,2 @@ const args = lastArgs; | ||
} | ||
function startTimer(pendingFunc, wait) { | ||
@@ -168,6 +152,4 @@ if (useRAF) { | ||
} | ||
return setTimeout(pendingFunc, wait); | ||
} | ||
function cancelTimer(id) { | ||
@@ -177,15 +159,12 @@ if (useRAF) { | ||
} | ||
clearTimeout(id); | ||
} | ||
function leadingEdge(time) { | ||
// Reset any `maxWait` timer. | ||
lastInvokeTime = time; // Start the timer for the trailing edge. | ||
timerId = startTimer(timerExpired, wait); // Invoke the leading edge. | ||
lastInvokeTime = time; | ||
// Start the timer for the trailing edge. | ||
timerId = startTimer(timerExpired, wait); | ||
// Invoke the leading edge. | ||
return leading ? invokeFunc(time) : result; | ||
} | ||
function remainingWait(time) { | ||
@@ -197,35 +176,28 @@ const timeSinceLastCall = time - lastCallTime; | ||
} | ||
function shouldInvoke(time) { | ||
const timeSinceLastCall = time - lastCallTime; | ||
const timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the | ||
const timeSinceLastInvoke = time - lastInvokeTime; | ||
// Either this is the first call, activity has stopped and we're at the | ||
// trailing edge, the system time has gone backwards and we're treating | ||
// it as the trailing edge, or we've hit the `maxWait` limit. | ||
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; | ||
} | ||
function timerExpired() { | ||
const time = Date.now(); | ||
if (shouldInvoke(time)) { | ||
return trailingEdge(time); | ||
} // Restart the timer. | ||
} | ||
// Restart the timer. | ||
timerId = startTimer(timerExpired, remainingWait(time)); | ||
} | ||
function trailingEdge(time) { | ||
timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been | ||
timerId = undefined; | ||
// Only invoke if we have `lastArgs` which means `func` has been | ||
// debounced at least once. | ||
if (trailing && lastArgs) { | ||
return invokeFunc(time); | ||
} | ||
lastArgs = lastThis = undefined; | ||
return result; | ||
} | ||
function cancel() { | ||
@@ -235,22 +207,20 @@ if (timerId !== undefined) { | ||
} | ||
lastInvokeTime = 0; | ||
lastArgs = lastCallTime = lastThis = timerId = undefined; | ||
} | ||
function flush() { | ||
return timerId === undefined ? result : trailingEdge(Date.now()); | ||
} | ||
function pending() { | ||
return timerId !== undefined; | ||
} | ||
function debounced(...args) { | ||
function debounced() { | ||
const time = Date.now(); | ||
const isInvoking = shouldInvoke(time); | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
lastArgs = args; | ||
lastThis = this; | ||
lastCallTime = time; | ||
if (isInvoking) { | ||
@@ -260,3 +230,2 @@ if (timerId === undefined) { | ||
} | ||
if (maxing) { | ||
@@ -268,10 +237,7 @@ // Handle invocations in a tight loop. | ||
} | ||
if (timerId === undefined) { | ||
timerId = startTimer(timerExpired, wait); | ||
} | ||
return result; | ||
} | ||
debounced.cancel = cancel; | ||
@@ -288,11 +254,11 @@ debounced.flush = flush; | ||
} | ||
if (!isObject(target[key]) || // `target[key]` is not an object | ||
!isObject(origin[key]) || // `target[key]` is not an object | ||
if (!isObject(target[key]) || | ||
// `target[key]` is not an object | ||
!isObject(origin[key]) || | ||
// `target[key]` is not an object | ||
!(key in origin) // `key` is not in the origin object | ||
) { | ||
origin[key] = target[key]; | ||
continue; | ||
} | ||
origin[key] = target[key]; | ||
continue; | ||
} | ||
if (isPlainObject(target[key]) || isArray(target[key])) { | ||
@@ -303,11 +269,11 @@ baseMerge(origin[key], target[key]); | ||
} | ||
function merge(origin, ...others) { | ||
function merge(origin) { | ||
const result = Object.assign({}, origin); | ||
for (var _len = arguments.length, others = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
others[_key - 1] = arguments[_key]; | ||
} | ||
if (!others.length) return result; | ||
for (const item of others) { | ||
baseMerge(result, item); | ||
} | ||
return result; | ||
@@ -320,11 +286,8 @@ } | ||
*/ | ||
function throttle(func, wait, options) { | ||
let leading = true; | ||
let trailing = true; | ||
if (typeof func !== 'function') { | ||
throw new TypeError('Expected a function'); | ||
} | ||
if (isObject(options)) { | ||
@@ -334,3 +297,2 @@ leading = 'leading' in options ? !!options.leading : leading; | ||
} | ||
return debounce(func, wait, { | ||
@@ -343,7 +305,8 @@ leading, | ||
var useDebouncePlugin = definePlugin((queryInstance, { | ||
debounceInterval, | ||
debounceOptions, | ||
manual | ||
}) => { | ||
var useDebouncePlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
debounceInterval, | ||
debounceOptions, | ||
manual | ||
} = _ref; | ||
const initialAutoRunFlag = vueDemi.ref(false); | ||
@@ -354,26 +317,25 @@ const debouncedRun = vueDemi.ref(); | ||
const originRunRef = vueDemi.ref(queryInstance.context.runAsync); | ||
if (!manual) { | ||
initialAutoRunFlag.value = true; | ||
} | ||
vueDemi.watchEffect(onInvalidate => { | ||
if (isNil(debounceIntervalRef.value)) return; | ||
debouncedRun.value = debounce(callback => callback(), debounceIntervalRef.value, debounceOptionsRef.value); | ||
queryInstance.context.runAsync = (...args) => new Promise((resolve, reject) => { | ||
if (initialAutoRunFlag.value) { | ||
initialAutoRunFlag.value = false; | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
} else { | ||
debouncedRun.value(() => { | ||
queryInstance.context.runAsync = function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return new Promise((resolve, reject) => { | ||
if (initialAutoRunFlag.value) { | ||
initialAutoRunFlag.value = false; | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
}); | ||
} | ||
}); | ||
} else { | ||
debouncedRun.value(() => { | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
}); | ||
} | ||
}); | ||
}; | ||
onInvalidate(() => { | ||
var _debouncedRun$value; | ||
(_debouncedRun$value = debouncedRun.value) === null || _debouncedRun$value === void 0 ? void 0 : _debouncedRun$value.cancel(); | ||
debouncedRun.value?.cancel(); | ||
queryInstance.context.runAsync = originRunRef.value; | ||
@@ -384,14 +346,12 @@ }); | ||
onCancel() { | ||
var _debouncedRun$value2; | ||
(_debouncedRun$value2 = debouncedRun.value) === null || _debouncedRun$value2 === void 0 ? void 0 : _debouncedRun$value2.cancel(); | ||
debouncedRun.value?.cancel(); | ||
} | ||
}; | ||
}); | ||
var useErrorRetryPlugin = definePlugin((queryInstance, { | ||
errorRetryCount = 0, | ||
errorRetryInterval = 0 | ||
}) => { | ||
var useErrorRetryPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
errorRetryCount = 0, | ||
errorRetryInterval = 0 | ||
} = _ref; | ||
const retryTimer = vueDemi.ref(); | ||
@@ -401,8 +361,7 @@ const retriedCount = vueDemi.ref(0); | ||
const errorRetryIntervalRef = vueDemi.computed(() => refToRaw(errorRetryInterval)); | ||
let isRetrying = false; // reset retried count | ||
let isRetrying = false; | ||
// reset retried count | ||
const resetRetriedCount = () => { | ||
retriedCount.value = 0; | ||
}; | ||
const actualErrorRetryInterval = vueDemi.computed(() => { | ||
@@ -412,14 +371,13 @@ if (errorRetryIntervalRef.value) return errorRetryIntervalRef.value; | ||
const minCoefficient = 1; | ||
const maxCoefficient = 9; // When retrying for the first time, in order to avoid the coefficient being 0 | ||
const maxCoefficient = 9; | ||
// When retrying for the first time, in order to avoid the coefficient being 0 | ||
// so replace 0 with 2, the coefficient range will become 1 - 2 | ||
const coefficient = Math.floor(Math.random() * 2 ** Math.min(retriedCount.value, maxCoefficient) + minCoefficient); | ||
return baseTime * coefficient; | ||
}); | ||
const errorRetryHooks = () => { | ||
let timerId; | ||
const isInfiniteRetry = errorRetryCountRef.value === -1; | ||
const hasRetryCount = retriedCount.value < errorRetryCountRef.value; // if errorRetryCount is -1, it will retry the request until it success | ||
const hasRetryCount = retriedCount.value < errorRetryCountRef.value; | ||
// if errorRetryCount is -1, it will retry the request until it success | ||
if (isInfiniteRetry || hasRetryCount) { | ||
@@ -432,7 +390,5 @@ if (!isInfiniteRetry) retriedCount.value += 1; | ||
} | ||
return () => timerId && clearTimeout(timerId); | ||
}; // clear retryTimer | ||
}; | ||
// clear retryTimer | ||
const clearTimer = () => { | ||
@@ -443,3 +399,2 @@ if (retryTimer.value) { | ||
}; | ||
return { | ||
@@ -450,15 +405,11 @@ onBefore() { | ||
} | ||
isRetrying = false; | ||
clearTimer(); | ||
}, | ||
onSuccess() { | ||
resetRetriedCount(); | ||
}, | ||
onError() { | ||
retryTimer.value = errorRetryHooks(); | ||
}, | ||
onCancel() { | ||
@@ -469,11 +420,11 @@ // TODO: Whether to reset the count when `onCancel` | ||
} | ||
}; | ||
}); | ||
var useReadyPlugin = definePlugin((queryInstance, { | ||
ready = vueDemi.ref(true), | ||
manual, | ||
defaultParams = [] | ||
}) => { | ||
var useReadyPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
ready = vueDemi.ref(true), | ||
manual, | ||
defaultParams = [] | ||
} = _ref; | ||
// watch ready | ||
@@ -489,3 +440,4 @@ vueDemi.watch(ready, val => { | ||
onBefore() { | ||
if (!ready.value) { | ||
const readyFlag = isFunction(ready) ? ready() : ready.value; | ||
if (!readyFlag) { | ||
queryInstance.loading.value = false; | ||
@@ -497,29 +449,29 @@ return { | ||
} | ||
}; | ||
}); | ||
var useRefreshDepsPlugin = definePlugin((queryInstance, { | ||
refreshDeps = [], | ||
refreshDepsAction, | ||
manual | ||
}) => { | ||
var useRefreshDepsPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
refreshDeps, | ||
refreshDepsAction, | ||
manual | ||
} = _ref; | ||
if (refreshDeps === undefined || isArray(refreshDeps) && refreshDeps.length === 0) return {}; | ||
const deps = isArray(refreshDeps) ? refreshDeps : [refreshDeps]; | ||
// watch refreshDeps | ||
if (refreshDeps !== null && refreshDeps !== void 0 && refreshDeps.length) { | ||
vueDemi.watch(refreshDeps, () => { | ||
if (refreshDepsAction) { | ||
refreshDepsAction(); | ||
} else { | ||
!manual && queryInstance.context.refresh(); | ||
} | ||
}); | ||
} | ||
vueDemi.watch(deps, () => { | ||
if (refreshDepsAction) { | ||
refreshDepsAction(); | ||
} else { | ||
!manual && queryInstance.context.refresh(); | ||
} | ||
}); | ||
return {}; | ||
}); | ||
var useThrottlePlugin = definePlugin((queryInstance, { | ||
throttleInterval, | ||
throttleOptions | ||
}) => { | ||
var useThrottlePlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
throttleInterval, | ||
throttleOptions | ||
} = _ref; | ||
const throttledRun = vueDemi.ref(); | ||
@@ -532,13 +484,14 @@ const throttleIntervalRef = vueDemi.computed(() => refToRaw(throttleInterval)); | ||
throttledRun.value = throttle(callback => callback(), throttleIntervalRef.value, throttleOptionsRef.value); | ||
queryInstance.context.runAsync = (...args) => new Promise((resolve, reject) => { | ||
throttledRun.value(() => { | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
queryInstance.context.runAsync = function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return new Promise((resolve, reject) => { | ||
throttledRun.value(() => { | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
}); | ||
}); | ||
}); | ||
}; | ||
onInvalidate(() => { | ||
var _throttledRun$value; | ||
(_throttledRun$value = throttledRun.value) === null || _throttledRun$value === void 0 ? void 0 : _throttledRun$value.cancel(); | ||
throttledRun.value?.cancel(); | ||
queryInstance.context.runAsync = originRunRef.value; | ||
@@ -549,7 +502,4 @@ }); | ||
onCancel() { | ||
var _throttledRun$value2; | ||
(_throttledRun$value2 = throttledRun.value) === null || _throttledRun$value2 === void 0 ? void 0 : _throttledRun$value2.cancel(); | ||
throttledRun.value?.cancel(); | ||
} | ||
}; | ||
@@ -566,18 +516,13 @@ }); | ||
}; | ||
const composeMiddleware = (middleArray, hook) => { | ||
return () => { | ||
let next = hook; | ||
for (let i = middleArray.length; i-- > 0;) { | ||
next = middleArray[i](next); | ||
} | ||
return next(); | ||
}; | ||
}; | ||
const createQuery = (service, config, initialState) => { | ||
var _initialState$loading, _initialState$data; | ||
const { | ||
@@ -590,6 +535,6 @@ initialData, | ||
} = config; | ||
const loading = vueDemi.ref((_initialState$loading = initialState === null || initialState === void 0 ? void 0 : initialState.loading) !== null && _initialState$loading !== void 0 ? _initialState$loading : false); | ||
const data = vueDemi.shallowRef((_initialState$data = initialState === null || initialState === void 0 ? void 0 : initialState.data) !== null && _initialState$data !== void 0 ? _initialState$data : initialData); | ||
const error = vueDemi.shallowRef(initialState === null || initialState === void 0 ? void 0 : initialState.error); | ||
const params = vueDemi.ref(initialState === null || initialState === void 0 ? void 0 : initialState.params); | ||
const loading = vueDemi.ref((_initialState$loading = initialState?.loading) !== null && _initialState$loading !== void 0 ? _initialState$loading : false); | ||
const data = vueDemi.shallowRef((_initialState$data = initialState?.data) !== null && _initialState$data !== void 0 ? _initialState$data : initialData); | ||
const error = vueDemi.shallowRef(initialState?.error); | ||
const params = vueDemi.ref(initialState?.params); | ||
const plugins = vueDemi.ref([]); | ||
@@ -605,4 +550,6 @@ const status = vueDemi.shallowRef('pending'); | ||
}, []); | ||
const emit = (event, ...args) => { | ||
const emit = function (event) { | ||
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
args[_key - 1] = arguments[_key]; | ||
} | ||
if (event === 'onQuery') { | ||
@@ -615,14 +562,11 @@ const queryFn = plugins.value.map(i => i.onQuery).filter(Boolean); | ||
// @ts-ignore | ||
const res = plugins.value.map(i => { | ||
var _i$event; | ||
return (_i$event = i[event]) === null || _i$event === void 0 ? void 0 : _i$event.call(i, ...args); | ||
}); | ||
const res = plugins.value.map(i => i[event]?.(...args)); | ||
return Object.assign({}, ...res); | ||
} | ||
}; | ||
const count = vueDemi.ref(0); | ||
context.runAsync = async (...args) => { | ||
context.runAsync = async function () { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
setState({ | ||
@@ -639,3 +583,2 @@ loading: true, | ||
} = emit('onBefore', args); | ||
if (isBreak) { | ||
@@ -647,8 +590,5 @@ setState({ | ||
} | ||
onBefore === null || onBefore === void 0 ? void 0 : onBefore(args); | ||
onBefore?.(args); | ||
try { | ||
const serviceWrapper = () => new Promise(resolve => resolve(service(...params.value))); | ||
let { | ||
@@ -658,7 +598,5 @@ servicePromise | ||
/* istanbul ignore next */ | ||
if (!servicePromise) { | ||
servicePromise = serviceWrapper(); | ||
} | ||
const res = await servicePromise; | ||
@@ -673,5 +611,7 @@ if (currentCount !== count.value) return resolvedPromise(); | ||
emit('onSuccess', res, args); | ||
onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(res, args); | ||
emit('onAfter', args, res, undefined); | ||
onAfter === null || onAfter === void 0 ? void 0 : onAfter(args); | ||
onSuccess?.(res, args); | ||
if (currentCount === count.value) { | ||
emit('onAfter', args, res, undefined); | ||
} | ||
onAfter?.(args); | ||
return res; | ||
@@ -686,11 +626,12 @@ } catch (error) { | ||
emit('onError', error, args); | ||
onError === null || onError === void 0 ? void 0 : onError(error, args); | ||
emit('onAfter', args, undefined, error); | ||
onAfter === null || onAfter === void 0 ? void 0 : onAfter(args); | ||
onError?.(error, args); | ||
if (currentCount === count.value) { | ||
emit('onAfter', args, undefined, error); | ||
} | ||
onAfter?.(args); | ||
throw error; | ||
} | ||
}; | ||
context.run = (...args) => { | ||
context.runAsync(...args).catch(error => { | ||
context.run = function () { | ||
context.runAsync(...arguments).catch(error => { | ||
if (!onError) { | ||
@@ -701,3 +642,2 @@ console.error(error); | ||
}; | ||
context.cancel = () => { | ||
@@ -710,16 +650,11 @@ count.value += 1; | ||
}; | ||
context.refresh = () => { | ||
context.run(...(params.value || [])); | ||
}; | ||
context.refreshAsync = () => { | ||
return context.runAsync(...(params.value || [])); | ||
}; | ||
context.mutate = x => { | ||
const mutateData = isFunction(x) ? x(data.value) : x; | ||
const _mutateData = shallowCopy(mutateData); | ||
setState({ | ||
@@ -730,3 +665,2 @@ data: _mutateData | ||
}; | ||
return { | ||
@@ -743,5 +677,8 @@ status, | ||
function useQuery(service, options = {}, plugins) { | ||
function useQuery(service) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
let plugins = arguments.length > 2 ? arguments[2] : undefined; | ||
const injectedGlobalOptions = vueDemi.inject(GLOBAL_OPTIONS_PROVIDE_KEY, {}); | ||
const config = { ...getGlobalOptions(), | ||
const config = { | ||
...getGlobalOptions(), | ||
...injectedGlobalOptions, | ||
@@ -755,4 +692,4 @@ ...options | ||
const queryInstance = createQuery(service, config); | ||
queryInstance.plugins.value = plugins.map(i => i(queryInstance, config)); // initial run | ||
queryInstance.plugins.value = plugins.map(i => i(queryInstance, config)); | ||
// initial run | ||
if (!manual) { | ||
@@ -762,3 +699,2 @@ const params = queryInstance.params.value || defaultParams; | ||
} | ||
vueDemi.onUnmounted(() => { | ||
@@ -787,7 +723,3 @@ queryInstance.context.cancel(); | ||
const data = vueDemi.shallowRef(); | ||
const dataList = vueDemi.computed(() => { | ||
var _data$value; | ||
return ((_data$value = data.value) === null || _data$value === void 0 ? void 0 : _data$value.list) || []; | ||
}); | ||
const dataList = vueDemi.computed(() => data.value?.list || []); | ||
const loadingMore = vueDemi.ref(false); | ||
@@ -804,6 +736,6 @@ const isTriggerByLoadMore = vueDemi.ref(false); | ||
const currentData = await service(lastData); | ||
if (currentCount === count.value) { | ||
if (lastData) { | ||
data.value = { ...currentData, | ||
data.value = { | ||
...currentData, | ||
list: [...lastData.list, ...currentData.list] | ||
@@ -815,8 +747,8 @@ }; | ||
} | ||
return currentData; | ||
}, { ...restOptions, | ||
}, { | ||
...restOptions, | ||
defaultParams: [], | ||
refreshDepsAction: () => { | ||
if (restOptions !== null && restOptions !== void 0 && restOptions.refreshDepsAction) { | ||
if (restOptions?.refreshDepsAction) { | ||
restOptions.refreshDepsAction(); | ||
@@ -828,16 +760,9 @@ } else { | ||
onError: error => { | ||
var _restOptions$onError; | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onError = restOptions.onError) === null || _restOptions$onError === void 0 ? void 0 : _restOptions$onError.call(restOptions, error); | ||
restOptions?.onError?.(error); | ||
}, | ||
onSuccess: data => { | ||
var _restOptions$onSucces; | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onSucces = restOptions.onSuccess) === null || _restOptions$onSucces === void 0 ? void 0 : _restOptions$onSucces.call(restOptions, data); | ||
restOptions?.onSuccess?.(data); | ||
}, | ||
onBefore: () => { | ||
var _restOptions$onBefore; | ||
count.value += 1; | ||
if (isTriggerByLoadMore.value) { | ||
@@ -847,11 +772,8 @@ isTriggerByLoadMore.value = false; | ||
} | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onBefore = restOptions.onBefore) === null || _restOptions$onBefore === void 0 ? void 0 : _restOptions$onBefore.call(restOptions); | ||
restOptions?.onBefore?.(); | ||
}, | ||
onAfter: () => { | ||
var _restOptions$onAfter; | ||
loadingMore.value = false; | ||
isTriggerByLoadMore.value = false; | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onAfter = restOptions.onAfter) === null || _restOptions$onAfter === void 0 ? void 0 : _restOptions$onAfter.call(restOptions); | ||
restOptions?.onAfter?.(); | ||
} | ||
@@ -862,7 +784,5 @@ }, [useErrorRetryPlugin, useDebouncePlugin, useThrottlePlugin, useRefreshDepsPlugin, useReadyPlugin]); | ||
}); | ||
const loadMore = () => { | ||
loadMoreAsync().catch(() => {}); | ||
}; | ||
const loadMoreAsync = () => { | ||
@@ -872,27 +792,17 @@ if (noMore.value) { | ||
} | ||
isTriggerByLoadMore.value = true; | ||
return runAsync(data.value); | ||
}; | ||
const refresh = () => run(); | ||
const refreshAsync = () => runAsync(); | ||
const cancel = () => { | ||
count.value += 1; | ||
_cancel(); | ||
loadingMore.value = false; | ||
}; | ||
const mutate = x => { | ||
const mutateData = isFunction(x) ? x(data.value) : x; | ||
const _mutateData = shallowCopy(mutateData); | ||
data.value = _mutateData; | ||
}; | ||
return { | ||
@@ -939,3 +849,2 @@ data, | ||
} | ||
return () => { | ||
@@ -947,9 +856,10 @@ const index = listeners.get(key).indexOf(listener); | ||
var useCachePlugin = definePlugin((queryInstance, { | ||
cacheKey: customCacheKey, | ||
cacheTime = 600000, | ||
staleTime = 0, | ||
getCache: customGetCache, | ||
setCache: customSetCache | ||
}) => { | ||
var useCachePlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
cacheKey: customCacheKey, | ||
cacheTime = 600000, | ||
staleTime = 0, | ||
getCache: customGetCache, | ||
setCache: customSetCache | ||
} = _ref; | ||
if (!customCacheKey) return {}; | ||
@@ -959,3 +869,2 @@ const cacheKey = isFunction(customCacheKey) ? customCacheKey : () => customCacheKey; | ||
let currentQuery; | ||
const _getCache = key => { | ||
@@ -968,3 +877,2 @@ if (customGetCache) { | ||
}; | ||
const _setCache = (key, time, cacheData) => { | ||
@@ -976,25 +884,17 @@ if (customSetCache) { | ||
} | ||
trigger(key, cacheData.data); | ||
}; | ||
const isFresh = time => staleTime === -1 || time + staleTime > new Date().getTime(); // Returns a boolean indicating whether the object has the specified property as its own property | ||
const isFresh = time => staleTime === -1 || time + staleTime > new Date().getTime(); | ||
// Returns a boolean indicating whether the object has the specified property as its own property | ||
// (as opposed to inheriting it) | ||
const hasProp = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop); | ||
const subscribeCache = params => { | ||
const _cacheKey = cacheKey(params); | ||
return subscribe(_cacheKey, data => { | ||
queryInstance.data.value = data; | ||
}); | ||
}; // When initializing, restore if there is a cache | ||
}; | ||
// When initializing, restore if there is a cache | ||
const _cacheKey = cacheKey(); | ||
const cache = _getCache(_cacheKey); | ||
if (cache && hasProp(cache, 'data')) { | ||
@@ -1004,7 +904,5 @@ queryInstance.data.value = cache.data; | ||
} | ||
if (_cacheKey) { | ||
unSubscribe.value = subscribeCache(); | ||
} | ||
vueDemi.onUnmounted(() => { | ||
@@ -1016,10 +914,7 @@ unSubscribe.value(); | ||
const _cacheKey = cacheKey(params); | ||
const cache = _getCache(_cacheKey); | ||
if (!cache || !hasProp(cache, 'data')) { | ||
return {}; | ||
} // If it's fresh, stop the request | ||
} | ||
// If it's fresh, stop the request | ||
if (isFresh(cache.time)) { | ||
@@ -1037,14 +932,9 @@ queryInstance.data.value = cache.data; | ||
}, | ||
onQuery(service) { | ||
const params = queryInstance.params.value; | ||
const _cacheKey = cacheKey(params); | ||
let servicePromise = getCacheQuery(_cacheKey); | ||
if (servicePromise && servicePromise !== currentQuery) { | ||
return () => servicePromise; | ||
} | ||
servicePromise = service(); | ||
@@ -1055,9 +945,6 @@ currentQuery = servicePromise; | ||
}, | ||
onSuccess(data, params) { | ||
const _cacheKey = cacheKey(params); | ||
if (_cacheKey) { | ||
unSubscribe.value(); | ||
_setCache(_cacheKey, cacheTime, { | ||
@@ -1068,13 +955,9 @@ data, | ||
}); | ||
unSubscribe.value = subscribeCache(params); | ||
} | ||
}, | ||
onMutate(data) { | ||
const _cacheKey = cacheKey(queryInstance.params.value); | ||
if (_cacheKey) { | ||
unSubscribe.value(); | ||
_setCache(_cacheKey, cacheTime, { | ||
@@ -1085,7 +968,5 @@ data, | ||
}); | ||
unSubscribe.value = subscribeCache(queryInstance.params.value); | ||
} | ||
} | ||
}; | ||
@@ -1096,7 +977,5 @@ }); | ||
let timerId, stop; | ||
class Timer extends Promise { | ||
constructor(fn) { | ||
super(fn); | ||
this.cancel = () => { | ||
@@ -1107,5 +986,3 @@ stop(); | ||
} | ||
} | ||
return new Timer(resolve => { | ||
@@ -1116,11 +993,10 @@ stop = resolve; | ||
} | ||
function getCurrentTime() { | ||
return new Date().getTime(); | ||
} | ||
var useLoadingDelayPlugin = definePlugin((queryInstance, { | ||
loadingDelay = 0, | ||
loadingKeep = 0 | ||
}) => { | ||
var useLoadingDelayPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
loadingDelay = 0, | ||
loadingKeep = 0 | ||
} = _ref; | ||
const delayLoadingTimer = vueDemi.ref(() => {}); | ||
@@ -1131,6 +1007,4 @@ const loadingDelayRef = vueDemi.computed(() => refToRaw(loadingDelay)); | ||
let timeoutPromise = {}; | ||
const delayLoading = () => { | ||
let timerId; | ||
if (loadingDelayRef.value) { | ||
@@ -1143,6 +1017,4 @@ timerId = setTimeout(() => { | ||
} | ||
return () => timerId && clearTimeout(timerId); | ||
}; | ||
return { | ||
@@ -1155,15 +1027,11 @@ onBefore() { | ||
}, | ||
onQuery(service) { | ||
if (!loadingKeepRef.value) return () => service(); | ||
timeoutPromise = setTimeoutPromise(loadingKeepRef.value + loadingDelayRef.value); | ||
const _service = async () => { | ||
try { | ||
const res = await service(); | ||
if (getCurrentTime() - startTime <= loadingDelayRef.value) { | ||
timeoutPromise.cancel(); | ||
} | ||
return Promise.resolve(res); | ||
@@ -1174,10 +1042,7 @@ } catch (error) { | ||
} | ||
return Promise.reject(error); | ||
} | ||
}; | ||
const servicePromise = Promise.allSettled([_service(), timeoutPromise]).then(res => { | ||
const result = res[0]; | ||
if (result.status === 'fulfilled') { | ||
@@ -1191,22 +1056,16 @@ return result.value; | ||
}, | ||
onCancel() { | ||
delayLoadingTimer.value(); | ||
}, | ||
onAfter() { | ||
delayLoadingTimer.value(); | ||
} | ||
}; | ||
}); | ||
var _window; | ||
const FOCUS_LISTENER = new Set(); | ||
const VISIBLE_LISTENER = new Set(); | ||
const RECONNECT_LISTENER = new Set(); | ||
const subscriber = (listenerType, event) => { | ||
let listeners; | ||
switch (listenerType) { | ||
@@ -1216,7 +1075,5 @@ case 'FOCUS_LISTENER': | ||
break; | ||
case 'RECONNECT_LISTENER': | ||
listeners = RECONNECT_LISTENER; | ||
break; | ||
case 'VISIBLE_LISTENER': | ||
@@ -1226,3 +1083,2 @@ listeners = VISIBLE_LISTENER; | ||
} | ||
if (listeners.has(event)) return; | ||
@@ -1234,3 +1090,2 @@ listeners.add(event); | ||
}; | ||
const observer = listeners => { | ||
@@ -1242,5 +1097,3 @@ listeners.forEach(event => { | ||
/* istanbul ignore else */ | ||
if (!isServer && (_window = window) !== null && _window !== void 0 && _window.addEventListener) { | ||
if (!isServer && window?.addEventListener) { | ||
window.addEventListener('visibilitychange', () => { | ||
@@ -1256,8 +1109,9 @@ /* istanbul ignore else */ | ||
var usePollingPlugin = definePlugin((queryInstance, { | ||
pollingInterval, | ||
pollingWhenHidden = false, | ||
pollingWhenOffline = false, | ||
errorRetryCount = 0 | ||
}) => { | ||
var usePollingPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
pollingInterval, | ||
pollingWhenHidden = false, | ||
pollingWhenOffline = false, | ||
errorRetryCount = 0 | ||
} = _ref; | ||
const pollingTimer = vueDemi.ref(); | ||
@@ -1268,14 +1122,13 @@ const stopPollingWhenHiddenOrOffline = vueDemi.ref(false); | ||
const unsubscribeList = []; | ||
const addUnsubscribeList = event => { | ||
event && unsubscribeList.push(event); | ||
}; | ||
const isKeepPolling = () => { | ||
return (// pollingWhenHidden = true or pollingWhenHidden = false and document is visibility | ||
(pollingWhenHidden || isDocumentVisibility()) && ( // pollingWhenOffline = true or pollingWhenOffline = false and is online | ||
return ( | ||
// pollingWhenHidden = true or pollingWhenHidden = false and document is visibility | ||
(pollingWhenHidden || isDocumentVisibility()) && ( | ||
// pollingWhenOffline = true or pollingWhenOffline = false and is online | ||
pollingWhenOffline || isOnline()) | ||
); | ||
}; | ||
const polling = pollingFunc => { | ||
@@ -1285,3 +1138,2 @@ // if errorRetry is enabled, then skip this method | ||
let timerId; | ||
if (!isNil(pollingIntervalRef.value) && pollingIntervalRef.value >= 0) { | ||
@@ -1296,6 +1148,4 @@ if (isKeepPolling()) { | ||
} | ||
return () => timerId && clearTimeout(timerId); | ||
}; | ||
const rePolling = () => { | ||
@@ -1307,3 +1157,2 @@ if (stopPollingWhenHiddenOrOffline.value && isKeepPolling()) { | ||
}; | ||
vueDemi.watch(pollingIntervalRef, () => { | ||
@@ -1314,13 +1163,11 @@ if (pollingTimer.value) { | ||
} | ||
}); // subscribe polling | ||
}); | ||
// subscribe polling | ||
if (!pollingWhenHidden) { | ||
addUnsubscribeList(subscriber('VISIBLE_LISTENER', rePolling)); | ||
} // subscribe online when pollingWhenOffline is false | ||
} | ||
// subscribe online when pollingWhenOffline is false | ||
if (!pollingWhenOffline) { | ||
addUnsubscribeList(subscriber('RECONNECT_LISTENER', rePolling)); | ||
} | ||
vueDemi.onUnmounted(() => { | ||
@@ -1331,17 +1178,10 @@ unsubscribeList.forEach(unsubscribe => unsubscribe()); | ||
onBefore() { | ||
var _pollingTimer$value; | ||
(_pollingTimer$value = pollingTimer.value) === null || _pollingTimer$value === void 0 ? void 0 : _pollingTimer$value.call(pollingTimer); | ||
pollingTimer.value?.(); | ||
}, | ||
onCancel() { | ||
var _pollingTimer$value2; | ||
(_pollingTimer$value2 = pollingTimer.value) === null || _pollingTimer$value2 === void 0 ? void 0 : _pollingTimer$value2.call(pollingTimer); | ||
pollingTimer.value?.(); | ||
}, | ||
onAfter() { | ||
pollingTimer.value = polling(() => queryInstance.context.refresh()); | ||
} | ||
}; | ||
@@ -1352,6 +1192,6 @@ }); | ||
let running = false; | ||
return (...args) => { | ||
return function () { | ||
if (running) return; | ||
running = true; | ||
fn(...args); | ||
fn(...arguments); | ||
setTimeout(() => { | ||
@@ -1363,21 +1203,18 @@ running = false; | ||
var useRefreshOnWindowFocus = definePlugin((queryInstance, { | ||
refreshOnWindowFocus = false, | ||
refocusTimespan = 5000 | ||
}) => { | ||
var useRefreshOnWindowFocus = definePlugin((queryInstance, _ref) => { | ||
let { | ||
refreshOnWindowFocus = false, | ||
refocusTimespan = 5000 | ||
} = _ref; | ||
const refreshOnWindowFocusRef = vueDemi.computed(() => refToRaw(refreshOnWindowFocus)); | ||
const refocusTimespanRef = vueDemi.computed(() => refToRaw(refocusTimespan)); | ||
const unsubscribeList = []; | ||
const addUnsubscribeList = event => { | ||
event && unsubscribeList.push(event); | ||
}; | ||
const unsubscribe = () => { | ||
unsubscribeList.forEach(fn => fn()); | ||
}; | ||
vueDemi.watchEffect(() => { | ||
unsubscribe(); | ||
if (refreshOnWindowFocusRef.value) { | ||
@@ -1399,3 +1236,4 @@ const limitRefresh = limitTrigger(queryInstance.context.refresh, refocusTimespanRef.value); | ||
function usePagination(service, options = {}) { | ||
function usePagination(service) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
const defaultPaginationOptions = { | ||
@@ -1430,6 +1268,6 @@ currentKey: 'current', | ||
} = useRequest(service, finallyOptions); | ||
const paging = paginationParams => { | ||
const [oldPaginationParams, ...restParams] = params.value || []; | ||
const newPaginationParams = { ...oldPaginationParams, | ||
const newPaginationParams = { | ||
...oldPaginationParams, | ||
...paginationParams | ||
@@ -1439,5 +1277,4 @@ }; | ||
run(...mergerParams); | ||
}; // changeCurrent change current page (current: number) => void | ||
}; | ||
// changeCurrent change current page (current: number) => void | ||
const changeCurrent = current => { | ||
@@ -1447,5 +1284,4 @@ paging({ | ||
}); | ||
}; // changePageSize change pageSize (pageSize: number) => void | ||
}; | ||
// changePageSize change pageSize (pageSize: number) => void | ||
const changePageSize = pageSize => { | ||
@@ -1455,5 +1291,4 @@ paging({ | ||
}); | ||
}; // changePagination change current and pageSize (current: number, pageSize: number) => void | ||
}; | ||
// changePagination change current and pageSize (current: number, pageSize: number) => void | ||
const changePagination = (current, pageSize) => { | ||
@@ -1465,10 +1300,8 @@ paging({ | ||
}; | ||
const total = vueDemi.computed(() => get(data.value, totalKey, 0)); | ||
const current = vueDemi.computed({ | ||
get: () => { | ||
var _params$value$0$curre, _params$value, _params$value$; | ||
var _params$value$0$curre; | ||
return (// @ts-ignore | ||
(_params$value$0$curre = (_params$value = params.value) === null || _params$value === void 0 ? void 0 : (_params$value$ = _params$value[0]) === null || _params$value$ === void 0 ? void 0 : _params$value$[currentKey]) !== null && _params$value$0$curre !== void 0 ? _params$value$0$curre : finallyOptions.defaultParams[0][currentKey] | ||
(_params$value$0$curre = params.value?.[0]?.[currentKey]) !== null && _params$value$0$curre !== void 0 ? _params$value$0$curre : finallyOptions.defaultParams[0][currentKey] | ||
); | ||
@@ -1482,6 +1315,5 @@ }, | ||
get: () => { | ||
var _params$value$0$pageS, _params$value2, _params$value2$; | ||
var _params$value$0$pageS; | ||
return (// @ts-ignore | ||
(_params$value$0$pageS = (_params$value2 = params.value) === null || _params$value2 === void 0 ? void 0 : (_params$value2$ = _params$value2[0]) === null || _params$value2$ === void 0 ? void 0 : _params$value2$[pageSizeKey]) !== null && _params$value$0$pageS !== void 0 ? _params$value$0$pageS : finallyOptions.defaultParams[0][pageSizeKey] | ||
(_params$value$0$pageS = params.value?.[0]?.[pageSizeKey]) !== null && _params$value$0$pageS !== void 0 ? _params$value$0$pageS : finallyOptions.defaultParams[0][pageSizeKey] | ||
); | ||
@@ -1488,0 +1320,0 @@ }, |
@@ -23,21 +23,17 @@ import { isRef, ref, computed, watchEffect, watch, shallowRef, inject, onUnmounted, provide } from 'vue-demi'; | ||
const isDocumentVisibility = () => { | ||
var _window$document; | ||
if (isServer || isNil((_window$document = window.document) === null || _window$document === void 0 ? void 0 : _window$document.visibilityState)) return true; | ||
if (isServer || isNil(window.document?.visibilityState)) return true; | ||
return window.document.visibilityState === 'visible'; | ||
}; | ||
const isOnline = () => { | ||
var _ref, _window$navigator; | ||
return (_ref = !isServer && ((_window$navigator = window.navigator) === null || _window$navigator === void 0 ? void 0 : _window$navigator.onLine)) !== null && _ref !== void 0 ? _ref : true; | ||
var _ref; | ||
return (_ref = !isServer && window.navigator?.onLine) !== null && _ref !== void 0 ? _ref : true; | ||
}; | ||
const resolvedPromise = () => new Promise(() => {}); | ||
const get = (source, path, defaultValue = undefined) => { | ||
const get = function (source, path) { | ||
let defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; | ||
// a[3].b -> a.3.b | ||
const paths = path.replace(/\[(\d+)\]/g, '.$1').split('.'); | ||
let result = source; | ||
for (const p of paths) { | ||
result = Object(result)[p]; | ||
if (result === undefined) { | ||
@@ -47,3 +43,2 @@ return defaultValue; | ||
} | ||
return result; | ||
@@ -53,12 +48,10 @@ }; | ||
const result = Object.assign({}, object); | ||
for (const key of keys) { | ||
delete result[key]; | ||
} | ||
return result; | ||
} | ||
const warning = (message, throwError = false) => { | ||
const warning = function (message) { | ||
let throwError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; | ||
const msg = `Warning: [vue-request] ${message}`; | ||
if (throwError) { | ||
@@ -89,9 +82,8 @@ return new Error(msg); | ||
const oldCache = CACHE_MAP.get(cacheKey); | ||
if (oldCache !== null && oldCache !== void 0 && oldCache.timer) { | ||
if (oldCache?.timer) { | ||
clearTimeout(oldCache.timer); | ||
} | ||
const timer = setTimeout(() => CACHE_MAP.delete(cacheKey), cacheTime); | ||
CACHE_MAP.set(cacheKey, { ...data, | ||
CACHE_MAP.set(cacheKey, { | ||
...data, | ||
timer | ||
@@ -102,5 +94,3 @@ }); | ||
if (cacheKey) { | ||
var _CACHE_MAP$get; | ||
const timer = (_CACHE_MAP$get = CACHE_MAP.get(cacheKey)) === null || _CACHE_MAP$get === void 0 ? void 0 : _CACHE_MAP$get.timer; | ||
const timer = CACHE_MAP.get(cacheKey)?.timer; | ||
timer && clearTimeout(timer); | ||
@@ -123,3 +113,2 @@ CACHE_MAP.delete(cacheKey); | ||
*/ | ||
function debounce(func, wait, options) { | ||
@@ -130,12 +119,9 @@ let lastArgs, lastThis, maxWait, result, timerId, lastCallTime; | ||
let maxing = false; | ||
let trailing = true; // Bypass `requestAnimationFrame` by explicitly setting `wait=0`. | ||
let trailing = true; | ||
// Bypass `requestAnimationFrame` by explicitly setting `wait=0`. | ||
const useRAF = !wait && wait !== 0 && typeof window.requestAnimationFrame === 'function'; | ||
if (typeof func !== 'function') { | ||
throw new TypeError('Expected a function'); | ||
} | ||
wait = +wait || 0; | ||
if (isObject(options)) { | ||
@@ -147,3 +133,2 @@ leading = !!options.leading; | ||
} | ||
function invokeFunc(time) { | ||
@@ -157,3 +142,2 @@ const args = lastArgs; | ||
} | ||
function startTimer(pendingFunc, wait) { | ||
@@ -164,6 +148,4 @@ if (useRAF) { | ||
} | ||
return setTimeout(pendingFunc, wait); | ||
} | ||
function cancelTimer(id) { | ||
@@ -173,15 +155,12 @@ if (useRAF) { | ||
} | ||
clearTimeout(id); | ||
} | ||
function leadingEdge(time) { | ||
// Reset any `maxWait` timer. | ||
lastInvokeTime = time; // Start the timer for the trailing edge. | ||
timerId = startTimer(timerExpired, wait); // Invoke the leading edge. | ||
lastInvokeTime = time; | ||
// Start the timer for the trailing edge. | ||
timerId = startTimer(timerExpired, wait); | ||
// Invoke the leading edge. | ||
return leading ? invokeFunc(time) : result; | ||
} | ||
function remainingWait(time) { | ||
@@ -193,35 +172,28 @@ const timeSinceLastCall = time - lastCallTime; | ||
} | ||
function shouldInvoke(time) { | ||
const timeSinceLastCall = time - lastCallTime; | ||
const timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the | ||
const timeSinceLastInvoke = time - lastInvokeTime; | ||
// Either this is the first call, activity has stopped and we're at the | ||
// trailing edge, the system time has gone backwards and we're treating | ||
// it as the trailing edge, or we've hit the `maxWait` limit. | ||
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; | ||
} | ||
function timerExpired() { | ||
const time = Date.now(); | ||
if (shouldInvoke(time)) { | ||
return trailingEdge(time); | ||
} // Restart the timer. | ||
} | ||
// Restart the timer. | ||
timerId = startTimer(timerExpired, remainingWait(time)); | ||
} | ||
function trailingEdge(time) { | ||
timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been | ||
timerId = undefined; | ||
// Only invoke if we have `lastArgs` which means `func` has been | ||
// debounced at least once. | ||
if (trailing && lastArgs) { | ||
return invokeFunc(time); | ||
} | ||
lastArgs = lastThis = undefined; | ||
return result; | ||
} | ||
function cancel() { | ||
@@ -231,22 +203,20 @@ if (timerId !== undefined) { | ||
} | ||
lastInvokeTime = 0; | ||
lastArgs = lastCallTime = lastThis = timerId = undefined; | ||
} | ||
function flush() { | ||
return timerId === undefined ? result : trailingEdge(Date.now()); | ||
} | ||
function pending() { | ||
return timerId !== undefined; | ||
} | ||
function debounced(...args) { | ||
function debounced() { | ||
const time = Date.now(); | ||
const isInvoking = shouldInvoke(time); | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
lastArgs = args; | ||
lastThis = this; | ||
lastCallTime = time; | ||
if (isInvoking) { | ||
@@ -256,3 +226,2 @@ if (timerId === undefined) { | ||
} | ||
if (maxing) { | ||
@@ -264,10 +233,7 @@ // Handle invocations in a tight loop. | ||
} | ||
if (timerId === undefined) { | ||
timerId = startTimer(timerExpired, wait); | ||
} | ||
return result; | ||
} | ||
debounced.cancel = cancel; | ||
@@ -284,11 +250,11 @@ debounced.flush = flush; | ||
} | ||
if (!isObject(target[key]) || // `target[key]` is not an object | ||
!isObject(origin[key]) || // `target[key]` is not an object | ||
if (!isObject(target[key]) || | ||
// `target[key]` is not an object | ||
!isObject(origin[key]) || | ||
// `target[key]` is not an object | ||
!(key in origin) // `key` is not in the origin object | ||
) { | ||
origin[key] = target[key]; | ||
continue; | ||
} | ||
origin[key] = target[key]; | ||
continue; | ||
} | ||
if (isPlainObject(target[key]) || isArray(target[key])) { | ||
@@ -299,11 +265,11 @@ baseMerge(origin[key], target[key]); | ||
} | ||
function merge(origin, ...others) { | ||
function merge(origin) { | ||
const result = Object.assign({}, origin); | ||
for (var _len = arguments.length, others = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
others[_key - 1] = arguments[_key]; | ||
} | ||
if (!others.length) return result; | ||
for (const item of others) { | ||
baseMerge(result, item); | ||
} | ||
return result; | ||
@@ -316,11 +282,8 @@ } | ||
*/ | ||
function throttle(func, wait, options) { | ||
let leading = true; | ||
let trailing = true; | ||
if (typeof func !== 'function') { | ||
throw new TypeError('Expected a function'); | ||
} | ||
if (isObject(options)) { | ||
@@ -330,3 +293,2 @@ leading = 'leading' in options ? !!options.leading : leading; | ||
} | ||
return debounce(func, wait, { | ||
@@ -339,7 +301,8 @@ leading, | ||
var useDebouncePlugin = definePlugin((queryInstance, { | ||
debounceInterval, | ||
debounceOptions, | ||
manual | ||
}) => { | ||
var useDebouncePlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
debounceInterval, | ||
debounceOptions, | ||
manual | ||
} = _ref; | ||
const initialAutoRunFlag = ref(false); | ||
@@ -350,26 +313,25 @@ const debouncedRun = ref(); | ||
const originRunRef = ref(queryInstance.context.runAsync); | ||
if (!manual) { | ||
initialAutoRunFlag.value = true; | ||
} | ||
watchEffect(onInvalidate => { | ||
if (isNil(debounceIntervalRef.value)) return; | ||
debouncedRun.value = debounce(callback => callback(), debounceIntervalRef.value, debounceOptionsRef.value); | ||
queryInstance.context.runAsync = (...args) => new Promise((resolve, reject) => { | ||
if (initialAutoRunFlag.value) { | ||
initialAutoRunFlag.value = false; | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
} else { | ||
debouncedRun.value(() => { | ||
queryInstance.context.runAsync = function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return new Promise((resolve, reject) => { | ||
if (initialAutoRunFlag.value) { | ||
initialAutoRunFlag.value = false; | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
}); | ||
} | ||
}); | ||
} else { | ||
debouncedRun.value(() => { | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
}); | ||
} | ||
}); | ||
}; | ||
onInvalidate(() => { | ||
var _debouncedRun$value; | ||
(_debouncedRun$value = debouncedRun.value) === null || _debouncedRun$value === void 0 ? void 0 : _debouncedRun$value.cancel(); | ||
debouncedRun.value?.cancel(); | ||
queryInstance.context.runAsync = originRunRef.value; | ||
@@ -380,14 +342,12 @@ }); | ||
onCancel() { | ||
var _debouncedRun$value2; | ||
(_debouncedRun$value2 = debouncedRun.value) === null || _debouncedRun$value2 === void 0 ? void 0 : _debouncedRun$value2.cancel(); | ||
debouncedRun.value?.cancel(); | ||
} | ||
}; | ||
}); | ||
var useErrorRetryPlugin = definePlugin((queryInstance, { | ||
errorRetryCount = 0, | ||
errorRetryInterval = 0 | ||
}) => { | ||
var useErrorRetryPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
errorRetryCount = 0, | ||
errorRetryInterval = 0 | ||
} = _ref; | ||
const retryTimer = ref(); | ||
@@ -397,8 +357,7 @@ const retriedCount = ref(0); | ||
const errorRetryIntervalRef = computed(() => refToRaw(errorRetryInterval)); | ||
let isRetrying = false; // reset retried count | ||
let isRetrying = false; | ||
// reset retried count | ||
const resetRetriedCount = () => { | ||
retriedCount.value = 0; | ||
}; | ||
const actualErrorRetryInterval = computed(() => { | ||
@@ -408,14 +367,13 @@ if (errorRetryIntervalRef.value) return errorRetryIntervalRef.value; | ||
const minCoefficient = 1; | ||
const maxCoefficient = 9; // When retrying for the first time, in order to avoid the coefficient being 0 | ||
const maxCoefficient = 9; | ||
// When retrying for the first time, in order to avoid the coefficient being 0 | ||
// so replace 0 with 2, the coefficient range will become 1 - 2 | ||
const coefficient = Math.floor(Math.random() * 2 ** Math.min(retriedCount.value, maxCoefficient) + minCoefficient); | ||
return baseTime * coefficient; | ||
}); | ||
const errorRetryHooks = () => { | ||
let timerId; | ||
const isInfiniteRetry = errorRetryCountRef.value === -1; | ||
const hasRetryCount = retriedCount.value < errorRetryCountRef.value; // if errorRetryCount is -1, it will retry the request until it success | ||
const hasRetryCount = retriedCount.value < errorRetryCountRef.value; | ||
// if errorRetryCount is -1, it will retry the request until it success | ||
if (isInfiniteRetry || hasRetryCount) { | ||
@@ -428,7 +386,5 @@ if (!isInfiniteRetry) retriedCount.value += 1; | ||
} | ||
return () => timerId && clearTimeout(timerId); | ||
}; // clear retryTimer | ||
}; | ||
// clear retryTimer | ||
const clearTimer = () => { | ||
@@ -439,3 +395,2 @@ if (retryTimer.value) { | ||
}; | ||
return { | ||
@@ -446,15 +401,11 @@ onBefore() { | ||
} | ||
isRetrying = false; | ||
clearTimer(); | ||
}, | ||
onSuccess() { | ||
resetRetriedCount(); | ||
}, | ||
onError() { | ||
retryTimer.value = errorRetryHooks(); | ||
}, | ||
onCancel() { | ||
@@ -465,11 +416,11 @@ // TODO: Whether to reset the count when `onCancel` | ||
} | ||
}; | ||
}); | ||
var useReadyPlugin = definePlugin((queryInstance, { | ||
ready = ref(true), | ||
manual, | ||
defaultParams = [] | ||
}) => { | ||
var useReadyPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
ready = ref(true), | ||
manual, | ||
defaultParams = [] | ||
} = _ref; | ||
// watch ready | ||
@@ -485,3 +436,4 @@ watch(ready, val => { | ||
onBefore() { | ||
if (!ready.value) { | ||
const readyFlag = isFunction(ready) ? ready() : ready.value; | ||
if (!readyFlag) { | ||
queryInstance.loading.value = false; | ||
@@ -493,29 +445,29 @@ return { | ||
} | ||
}; | ||
}); | ||
var useRefreshDepsPlugin = definePlugin((queryInstance, { | ||
refreshDeps = [], | ||
refreshDepsAction, | ||
manual | ||
}) => { | ||
var useRefreshDepsPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
refreshDeps, | ||
refreshDepsAction, | ||
manual | ||
} = _ref; | ||
if (refreshDeps === undefined || isArray(refreshDeps) && refreshDeps.length === 0) return {}; | ||
const deps = isArray(refreshDeps) ? refreshDeps : [refreshDeps]; | ||
// watch refreshDeps | ||
if (refreshDeps !== null && refreshDeps !== void 0 && refreshDeps.length) { | ||
watch(refreshDeps, () => { | ||
if (refreshDepsAction) { | ||
refreshDepsAction(); | ||
} else { | ||
!manual && queryInstance.context.refresh(); | ||
} | ||
}); | ||
} | ||
watch(deps, () => { | ||
if (refreshDepsAction) { | ||
refreshDepsAction(); | ||
} else { | ||
!manual && queryInstance.context.refresh(); | ||
} | ||
}); | ||
return {}; | ||
}); | ||
var useThrottlePlugin = definePlugin((queryInstance, { | ||
throttleInterval, | ||
throttleOptions | ||
}) => { | ||
var useThrottlePlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
throttleInterval, | ||
throttleOptions | ||
} = _ref; | ||
const throttledRun = ref(); | ||
@@ -528,13 +480,14 @@ const throttleIntervalRef = computed(() => refToRaw(throttleInterval)); | ||
throttledRun.value = throttle(callback => callback(), throttleIntervalRef.value, throttleOptionsRef.value); | ||
queryInstance.context.runAsync = (...args) => new Promise((resolve, reject) => { | ||
throttledRun.value(() => { | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
queryInstance.context.runAsync = function () { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return new Promise((resolve, reject) => { | ||
throttledRun.value(() => { | ||
originRunRef.value(...args).then(resolve).catch(reject); | ||
}); | ||
}); | ||
}); | ||
}; | ||
onInvalidate(() => { | ||
var _throttledRun$value; | ||
(_throttledRun$value = throttledRun.value) === null || _throttledRun$value === void 0 ? void 0 : _throttledRun$value.cancel(); | ||
throttledRun.value?.cancel(); | ||
queryInstance.context.runAsync = originRunRef.value; | ||
@@ -545,7 +498,4 @@ }); | ||
onCancel() { | ||
var _throttledRun$value2; | ||
(_throttledRun$value2 = throttledRun.value) === null || _throttledRun$value2 === void 0 ? void 0 : _throttledRun$value2.cancel(); | ||
throttledRun.value?.cancel(); | ||
} | ||
}; | ||
@@ -562,18 +512,13 @@ }); | ||
}; | ||
const composeMiddleware = (middleArray, hook) => { | ||
return () => { | ||
let next = hook; | ||
for (let i = middleArray.length; i-- > 0;) { | ||
next = middleArray[i](next); | ||
} | ||
return next(); | ||
}; | ||
}; | ||
const createQuery = (service, config, initialState) => { | ||
var _initialState$loading, _initialState$data; | ||
const { | ||
@@ -586,6 +531,6 @@ initialData, | ||
} = config; | ||
const loading = ref((_initialState$loading = initialState === null || initialState === void 0 ? void 0 : initialState.loading) !== null && _initialState$loading !== void 0 ? _initialState$loading : false); | ||
const data = shallowRef((_initialState$data = initialState === null || initialState === void 0 ? void 0 : initialState.data) !== null && _initialState$data !== void 0 ? _initialState$data : initialData); | ||
const error = shallowRef(initialState === null || initialState === void 0 ? void 0 : initialState.error); | ||
const params = ref(initialState === null || initialState === void 0 ? void 0 : initialState.params); | ||
const loading = ref((_initialState$loading = initialState?.loading) !== null && _initialState$loading !== void 0 ? _initialState$loading : false); | ||
const data = shallowRef((_initialState$data = initialState?.data) !== null && _initialState$data !== void 0 ? _initialState$data : initialData); | ||
const error = shallowRef(initialState?.error); | ||
const params = ref(initialState?.params); | ||
const plugins = ref([]); | ||
@@ -601,4 +546,6 @@ const status = shallowRef('pending'); | ||
}, []); | ||
const emit = (event, ...args) => { | ||
const emit = function (event) { | ||
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
args[_key - 1] = arguments[_key]; | ||
} | ||
if (event === 'onQuery') { | ||
@@ -611,14 +558,11 @@ const queryFn = plugins.value.map(i => i.onQuery).filter(Boolean); | ||
// @ts-ignore | ||
const res = plugins.value.map(i => { | ||
var _i$event; | ||
return (_i$event = i[event]) === null || _i$event === void 0 ? void 0 : _i$event.call(i, ...args); | ||
}); | ||
const res = plugins.value.map(i => i[event]?.(...args)); | ||
return Object.assign({}, ...res); | ||
} | ||
}; | ||
const count = ref(0); | ||
context.runAsync = async (...args) => { | ||
context.runAsync = async function () { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
setState({ | ||
@@ -635,3 +579,2 @@ loading: true, | ||
} = emit('onBefore', args); | ||
if (isBreak) { | ||
@@ -643,8 +586,5 @@ setState({ | ||
} | ||
onBefore === null || onBefore === void 0 ? void 0 : onBefore(args); | ||
onBefore?.(args); | ||
try { | ||
const serviceWrapper = () => new Promise(resolve => resolve(service(...params.value))); | ||
let { | ||
@@ -654,7 +594,5 @@ servicePromise | ||
/* istanbul ignore next */ | ||
if (!servicePromise) { | ||
servicePromise = serviceWrapper(); | ||
} | ||
const res = await servicePromise; | ||
@@ -669,5 +607,7 @@ if (currentCount !== count.value) return resolvedPromise(); | ||
emit('onSuccess', res, args); | ||
onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(res, args); | ||
emit('onAfter', args, res, undefined); | ||
onAfter === null || onAfter === void 0 ? void 0 : onAfter(args); | ||
onSuccess?.(res, args); | ||
if (currentCount === count.value) { | ||
emit('onAfter', args, res, undefined); | ||
} | ||
onAfter?.(args); | ||
return res; | ||
@@ -682,11 +622,12 @@ } catch (error) { | ||
emit('onError', error, args); | ||
onError === null || onError === void 0 ? void 0 : onError(error, args); | ||
emit('onAfter', args, undefined, error); | ||
onAfter === null || onAfter === void 0 ? void 0 : onAfter(args); | ||
onError?.(error, args); | ||
if (currentCount === count.value) { | ||
emit('onAfter', args, undefined, error); | ||
} | ||
onAfter?.(args); | ||
throw error; | ||
} | ||
}; | ||
context.run = (...args) => { | ||
context.runAsync(...args).catch(error => { | ||
context.run = function () { | ||
context.runAsync(...arguments).catch(error => { | ||
if (!onError) { | ||
@@ -697,3 +638,2 @@ console.error(error); | ||
}; | ||
context.cancel = () => { | ||
@@ -706,16 +646,11 @@ count.value += 1; | ||
}; | ||
context.refresh = () => { | ||
context.run(...(params.value || [])); | ||
}; | ||
context.refreshAsync = () => { | ||
return context.runAsync(...(params.value || [])); | ||
}; | ||
context.mutate = x => { | ||
const mutateData = isFunction(x) ? x(data.value) : x; | ||
const _mutateData = shallowCopy(mutateData); | ||
setState({ | ||
@@ -726,3 +661,2 @@ data: _mutateData | ||
}; | ||
return { | ||
@@ -739,5 +673,8 @@ status, | ||
function useQuery(service, options = {}, plugins) { | ||
function useQuery(service) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
let plugins = arguments.length > 2 ? arguments[2] : undefined; | ||
const injectedGlobalOptions = inject(GLOBAL_OPTIONS_PROVIDE_KEY, {}); | ||
const config = { ...getGlobalOptions(), | ||
const config = { | ||
...getGlobalOptions(), | ||
...injectedGlobalOptions, | ||
@@ -751,4 +688,4 @@ ...options | ||
const queryInstance = createQuery(service, config); | ||
queryInstance.plugins.value = plugins.map(i => i(queryInstance, config)); // initial run | ||
queryInstance.plugins.value = plugins.map(i => i(queryInstance, config)); | ||
// initial run | ||
if (!manual) { | ||
@@ -758,3 +695,2 @@ const params = queryInstance.params.value || defaultParams; | ||
} | ||
onUnmounted(() => { | ||
@@ -783,7 +719,3 @@ queryInstance.context.cancel(); | ||
const data = shallowRef(); | ||
const dataList = computed(() => { | ||
var _data$value; | ||
return ((_data$value = data.value) === null || _data$value === void 0 ? void 0 : _data$value.list) || []; | ||
}); | ||
const dataList = computed(() => data.value?.list || []); | ||
const loadingMore = ref(false); | ||
@@ -800,6 +732,6 @@ const isTriggerByLoadMore = ref(false); | ||
const currentData = await service(lastData); | ||
if (currentCount === count.value) { | ||
if (lastData) { | ||
data.value = { ...currentData, | ||
data.value = { | ||
...currentData, | ||
list: [...lastData.list, ...currentData.list] | ||
@@ -811,8 +743,8 @@ }; | ||
} | ||
return currentData; | ||
}, { ...restOptions, | ||
}, { | ||
...restOptions, | ||
defaultParams: [], | ||
refreshDepsAction: () => { | ||
if (restOptions !== null && restOptions !== void 0 && restOptions.refreshDepsAction) { | ||
if (restOptions?.refreshDepsAction) { | ||
restOptions.refreshDepsAction(); | ||
@@ -824,16 +756,9 @@ } else { | ||
onError: error => { | ||
var _restOptions$onError; | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onError = restOptions.onError) === null || _restOptions$onError === void 0 ? void 0 : _restOptions$onError.call(restOptions, error); | ||
restOptions?.onError?.(error); | ||
}, | ||
onSuccess: data => { | ||
var _restOptions$onSucces; | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onSucces = restOptions.onSuccess) === null || _restOptions$onSucces === void 0 ? void 0 : _restOptions$onSucces.call(restOptions, data); | ||
restOptions?.onSuccess?.(data); | ||
}, | ||
onBefore: () => { | ||
var _restOptions$onBefore; | ||
count.value += 1; | ||
if (isTriggerByLoadMore.value) { | ||
@@ -843,11 +768,8 @@ isTriggerByLoadMore.value = false; | ||
} | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onBefore = restOptions.onBefore) === null || _restOptions$onBefore === void 0 ? void 0 : _restOptions$onBefore.call(restOptions); | ||
restOptions?.onBefore?.(); | ||
}, | ||
onAfter: () => { | ||
var _restOptions$onAfter; | ||
loadingMore.value = false; | ||
isTriggerByLoadMore.value = false; | ||
restOptions === null || restOptions === void 0 ? void 0 : (_restOptions$onAfter = restOptions.onAfter) === null || _restOptions$onAfter === void 0 ? void 0 : _restOptions$onAfter.call(restOptions); | ||
restOptions?.onAfter?.(); | ||
} | ||
@@ -858,7 +780,5 @@ }, [useErrorRetryPlugin, useDebouncePlugin, useThrottlePlugin, useRefreshDepsPlugin, useReadyPlugin]); | ||
}); | ||
const loadMore = () => { | ||
loadMoreAsync().catch(() => {}); | ||
}; | ||
const loadMoreAsync = () => { | ||
@@ -868,27 +788,17 @@ if (noMore.value) { | ||
} | ||
isTriggerByLoadMore.value = true; | ||
return runAsync(data.value); | ||
}; | ||
const refresh = () => run(); | ||
const refreshAsync = () => runAsync(); | ||
const cancel = () => { | ||
count.value += 1; | ||
_cancel(); | ||
loadingMore.value = false; | ||
}; | ||
const mutate = x => { | ||
const mutateData = isFunction(x) ? x(data.value) : x; | ||
const _mutateData = shallowCopy(mutateData); | ||
data.value = _mutateData; | ||
}; | ||
return { | ||
@@ -935,3 +845,2 @@ data, | ||
} | ||
return () => { | ||
@@ -943,9 +852,10 @@ const index = listeners.get(key).indexOf(listener); | ||
var useCachePlugin = definePlugin((queryInstance, { | ||
cacheKey: customCacheKey, | ||
cacheTime = 600000, | ||
staleTime = 0, | ||
getCache: customGetCache, | ||
setCache: customSetCache | ||
}) => { | ||
var useCachePlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
cacheKey: customCacheKey, | ||
cacheTime = 600000, | ||
staleTime = 0, | ||
getCache: customGetCache, | ||
setCache: customSetCache | ||
} = _ref; | ||
if (!customCacheKey) return {}; | ||
@@ -955,3 +865,2 @@ const cacheKey = isFunction(customCacheKey) ? customCacheKey : () => customCacheKey; | ||
let currentQuery; | ||
const _getCache = key => { | ||
@@ -964,3 +873,2 @@ if (customGetCache) { | ||
}; | ||
const _setCache = (key, time, cacheData) => { | ||
@@ -972,25 +880,17 @@ if (customSetCache) { | ||
} | ||
trigger(key, cacheData.data); | ||
}; | ||
const isFresh = time => staleTime === -1 || time + staleTime > new Date().getTime(); // Returns a boolean indicating whether the object has the specified property as its own property | ||
const isFresh = time => staleTime === -1 || time + staleTime > new Date().getTime(); | ||
// Returns a boolean indicating whether the object has the specified property as its own property | ||
// (as opposed to inheriting it) | ||
const hasProp = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop); | ||
const subscribeCache = params => { | ||
const _cacheKey = cacheKey(params); | ||
return subscribe(_cacheKey, data => { | ||
queryInstance.data.value = data; | ||
}); | ||
}; // When initializing, restore if there is a cache | ||
}; | ||
// When initializing, restore if there is a cache | ||
const _cacheKey = cacheKey(); | ||
const cache = _getCache(_cacheKey); | ||
if (cache && hasProp(cache, 'data')) { | ||
@@ -1000,7 +900,5 @@ queryInstance.data.value = cache.data; | ||
} | ||
if (_cacheKey) { | ||
unSubscribe.value = subscribeCache(); | ||
} | ||
onUnmounted(() => { | ||
@@ -1012,10 +910,7 @@ unSubscribe.value(); | ||
const _cacheKey = cacheKey(params); | ||
const cache = _getCache(_cacheKey); | ||
if (!cache || !hasProp(cache, 'data')) { | ||
return {}; | ||
} // If it's fresh, stop the request | ||
} | ||
// If it's fresh, stop the request | ||
if (isFresh(cache.time)) { | ||
@@ -1033,14 +928,9 @@ queryInstance.data.value = cache.data; | ||
}, | ||
onQuery(service) { | ||
const params = queryInstance.params.value; | ||
const _cacheKey = cacheKey(params); | ||
let servicePromise = getCacheQuery(_cacheKey); | ||
if (servicePromise && servicePromise !== currentQuery) { | ||
return () => servicePromise; | ||
} | ||
servicePromise = service(); | ||
@@ -1051,9 +941,6 @@ currentQuery = servicePromise; | ||
}, | ||
onSuccess(data, params) { | ||
const _cacheKey = cacheKey(params); | ||
if (_cacheKey) { | ||
unSubscribe.value(); | ||
_setCache(_cacheKey, cacheTime, { | ||
@@ -1064,13 +951,9 @@ data, | ||
}); | ||
unSubscribe.value = subscribeCache(params); | ||
} | ||
}, | ||
onMutate(data) { | ||
const _cacheKey = cacheKey(queryInstance.params.value); | ||
if (_cacheKey) { | ||
unSubscribe.value(); | ||
_setCache(_cacheKey, cacheTime, { | ||
@@ -1081,7 +964,5 @@ data, | ||
}); | ||
unSubscribe.value = subscribeCache(queryInstance.params.value); | ||
} | ||
} | ||
}; | ||
@@ -1092,7 +973,5 @@ }); | ||
let timerId, stop; | ||
class Timer extends Promise { | ||
constructor(fn) { | ||
super(fn); | ||
this.cancel = () => { | ||
@@ -1103,5 +982,3 @@ stop(); | ||
} | ||
} | ||
return new Timer(resolve => { | ||
@@ -1112,11 +989,10 @@ stop = resolve; | ||
} | ||
function getCurrentTime() { | ||
return new Date().getTime(); | ||
} | ||
var useLoadingDelayPlugin = definePlugin((queryInstance, { | ||
loadingDelay = 0, | ||
loadingKeep = 0 | ||
}) => { | ||
var useLoadingDelayPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
loadingDelay = 0, | ||
loadingKeep = 0 | ||
} = _ref; | ||
const delayLoadingTimer = ref(() => {}); | ||
@@ -1127,6 +1003,4 @@ const loadingDelayRef = computed(() => refToRaw(loadingDelay)); | ||
let timeoutPromise = {}; | ||
const delayLoading = () => { | ||
let timerId; | ||
if (loadingDelayRef.value) { | ||
@@ -1139,6 +1013,4 @@ timerId = setTimeout(() => { | ||
} | ||
return () => timerId && clearTimeout(timerId); | ||
}; | ||
return { | ||
@@ -1151,15 +1023,11 @@ onBefore() { | ||
}, | ||
onQuery(service) { | ||
if (!loadingKeepRef.value) return () => service(); | ||
timeoutPromise = setTimeoutPromise(loadingKeepRef.value + loadingDelayRef.value); | ||
const _service = async () => { | ||
try { | ||
const res = await service(); | ||
if (getCurrentTime() - startTime <= loadingDelayRef.value) { | ||
timeoutPromise.cancel(); | ||
} | ||
return Promise.resolve(res); | ||
@@ -1170,10 +1038,7 @@ } catch (error) { | ||
} | ||
return Promise.reject(error); | ||
} | ||
}; | ||
const servicePromise = Promise.allSettled([_service(), timeoutPromise]).then(res => { | ||
const result = res[0]; | ||
if (result.status === 'fulfilled') { | ||
@@ -1187,22 +1052,16 @@ return result.value; | ||
}, | ||
onCancel() { | ||
delayLoadingTimer.value(); | ||
}, | ||
onAfter() { | ||
delayLoadingTimer.value(); | ||
} | ||
}; | ||
}); | ||
var _window; | ||
const FOCUS_LISTENER = new Set(); | ||
const VISIBLE_LISTENER = new Set(); | ||
const RECONNECT_LISTENER = new Set(); | ||
const subscriber = (listenerType, event) => { | ||
let listeners; | ||
switch (listenerType) { | ||
@@ -1212,7 +1071,5 @@ case 'FOCUS_LISTENER': | ||
break; | ||
case 'RECONNECT_LISTENER': | ||
listeners = RECONNECT_LISTENER; | ||
break; | ||
case 'VISIBLE_LISTENER': | ||
@@ -1222,3 +1079,2 @@ listeners = VISIBLE_LISTENER; | ||
} | ||
if (listeners.has(event)) return; | ||
@@ -1230,3 +1086,2 @@ listeners.add(event); | ||
}; | ||
const observer = listeners => { | ||
@@ -1238,5 +1093,3 @@ listeners.forEach(event => { | ||
/* istanbul ignore else */ | ||
if (!isServer && (_window = window) !== null && _window !== void 0 && _window.addEventListener) { | ||
if (!isServer && window?.addEventListener) { | ||
window.addEventListener('visibilitychange', () => { | ||
@@ -1252,8 +1105,9 @@ /* istanbul ignore else */ | ||
var usePollingPlugin = definePlugin((queryInstance, { | ||
pollingInterval, | ||
pollingWhenHidden = false, | ||
pollingWhenOffline = false, | ||
errorRetryCount = 0 | ||
}) => { | ||
var usePollingPlugin = definePlugin((queryInstance, _ref) => { | ||
let { | ||
pollingInterval, | ||
pollingWhenHidden = false, | ||
pollingWhenOffline = false, | ||
errorRetryCount = 0 | ||
} = _ref; | ||
const pollingTimer = ref(); | ||
@@ -1264,14 +1118,13 @@ const stopPollingWhenHiddenOrOffline = ref(false); | ||
const unsubscribeList = []; | ||
const addUnsubscribeList = event => { | ||
event && unsubscribeList.push(event); | ||
}; | ||
const isKeepPolling = () => { | ||
return (// pollingWhenHidden = true or pollingWhenHidden = false and document is visibility | ||
(pollingWhenHidden || isDocumentVisibility()) && ( // pollingWhenOffline = true or pollingWhenOffline = false and is online | ||
return ( | ||
// pollingWhenHidden = true or pollingWhenHidden = false and document is visibility | ||
(pollingWhenHidden || isDocumentVisibility()) && ( | ||
// pollingWhenOffline = true or pollingWhenOffline = false and is online | ||
pollingWhenOffline || isOnline()) | ||
); | ||
}; | ||
const polling = pollingFunc => { | ||
@@ -1281,3 +1134,2 @@ // if errorRetry is enabled, then skip this method | ||
let timerId; | ||
if (!isNil(pollingIntervalRef.value) && pollingIntervalRef.value >= 0) { | ||
@@ -1292,6 +1144,4 @@ if (isKeepPolling()) { | ||
} | ||
return () => timerId && clearTimeout(timerId); | ||
}; | ||
const rePolling = () => { | ||
@@ -1303,3 +1153,2 @@ if (stopPollingWhenHiddenOrOffline.value && isKeepPolling()) { | ||
}; | ||
watch(pollingIntervalRef, () => { | ||
@@ -1310,13 +1159,11 @@ if (pollingTimer.value) { | ||
} | ||
}); // subscribe polling | ||
}); | ||
// subscribe polling | ||
if (!pollingWhenHidden) { | ||
addUnsubscribeList(subscriber('VISIBLE_LISTENER', rePolling)); | ||
} // subscribe online when pollingWhenOffline is false | ||
} | ||
// subscribe online when pollingWhenOffline is false | ||
if (!pollingWhenOffline) { | ||
addUnsubscribeList(subscriber('RECONNECT_LISTENER', rePolling)); | ||
} | ||
onUnmounted(() => { | ||
@@ -1327,17 +1174,10 @@ unsubscribeList.forEach(unsubscribe => unsubscribe()); | ||
onBefore() { | ||
var _pollingTimer$value; | ||
(_pollingTimer$value = pollingTimer.value) === null || _pollingTimer$value === void 0 ? void 0 : _pollingTimer$value.call(pollingTimer); | ||
pollingTimer.value?.(); | ||
}, | ||
onCancel() { | ||
var _pollingTimer$value2; | ||
(_pollingTimer$value2 = pollingTimer.value) === null || _pollingTimer$value2 === void 0 ? void 0 : _pollingTimer$value2.call(pollingTimer); | ||
pollingTimer.value?.(); | ||
}, | ||
onAfter() { | ||
pollingTimer.value = polling(() => queryInstance.context.refresh()); | ||
} | ||
}; | ||
@@ -1348,6 +1188,6 @@ }); | ||
let running = false; | ||
return (...args) => { | ||
return function () { | ||
if (running) return; | ||
running = true; | ||
fn(...args); | ||
fn(...arguments); | ||
setTimeout(() => { | ||
@@ -1359,21 +1199,18 @@ running = false; | ||
var useRefreshOnWindowFocus = definePlugin((queryInstance, { | ||
refreshOnWindowFocus = false, | ||
refocusTimespan = 5000 | ||
}) => { | ||
var useRefreshOnWindowFocus = definePlugin((queryInstance, _ref) => { | ||
let { | ||
refreshOnWindowFocus = false, | ||
refocusTimespan = 5000 | ||
} = _ref; | ||
const refreshOnWindowFocusRef = computed(() => refToRaw(refreshOnWindowFocus)); | ||
const refocusTimespanRef = computed(() => refToRaw(refocusTimespan)); | ||
const unsubscribeList = []; | ||
const addUnsubscribeList = event => { | ||
event && unsubscribeList.push(event); | ||
}; | ||
const unsubscribe = () => { | ||
unsubscribeList.forEach(fn => fn()); | ||
}; | ||
watchEffect(() => { | ||
unsubscribe(); | ||
if (refreshOnWindowFocusRef.value) { | ||
@@ -1395,3 +1232,4 @@ const limitRefresh = limitTrigger(queryInstance.context.refresh, refocusTimespanRef.value); | ||
function usePagination(service, options = {}) { | ||
function usePagination(service) { | ||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
const defaultPaginationOptions = { | ||
@@ -1426,6 +1264,6 @@ currentKey: 'current', | ||
} = useRequest(service, finallyOptions); | ||
const paging = paginationParams => { | ||
const [oldPaginationParams, ...restParams] = params.value || []; | ||
const newPaginationParams = { ...oldPaginationParams, | ||
const newPaginationParams = { | ||
...oldPaginationParams, | ||
...paginationParams | ||
@@ -1435,5 +1273,4 @@ }; | ||
run(...mergerParams); | ||
}; // changeCurrent change current page (current: number) => void | ||
}; | ||
// changeCurrent change current page (current: number) => void | ||
const changeCurrent = current => { | ||
@@ -1443,5 +1280,4 @@ paging({ | ||
}); | ||
}; // changePageSize change pageSize (pageSize: number) => void | ||
}; | ||
// changePageSize change pageSize (pageSize: number) => void | ||
const changePageSize = pageSize => { | ||
@@ -1451,5 +1287,4 @@ paging({ | ||
}); | ||
}; // changePagination change current and pageSize (current: number, pageSize: number) => void | ||
}; | ||
// changePagination change current and pageSize (current: number, pageSize: number) => void | ||
const changePagination = (current, pageSize) => { | ||
@@ -1461,10 +1296,8 @@ paging({ | ||
}; | ||
const total = computed(() => get(data.value, totalKey, 0)); | ||
const current = computed({ | ||
get: () => { | ||
var _params$value$0$curre, _params$value, _params$value$; | ||
var _params$value$0$curre; | ||
return (// @ts-ignore | ||
(_params$value$0$curre = (_params$value = params.value) === null || _params$value === void 0 ? void 0 : (_params$value$ = _params$value[0]) === null || _params$value$ === void 0 ? void 0 : _params$value$[currentKey]) !== null && _params$value$0$curre !== void 0 ? _params$value$0$curre : finallyOptions.defaultParams[0][currentKey] | ||
(_params$value$0$curre = params.value?.[0]?.[currentKey]) !== null && _params$value$0$curre !== void 0 ? _params$value$0$curre : finallyOptions.defaultParams[0][currentKey] | ||
); | ||
@@ -1478,6 +1311,5 @@ }, | ||
get: () => { | ||
var _params$value$0$pageS, _params$value2, _params$value2$; | ||
var _params$value$0$pageS; | ||
return (// @ts-ignore | ||
(_params$value$0$pageS = (_params$value2 = params.value) === null || _params$value2 === void 0 ? void 0 : (_params$value2$ = _params$value2[0]) === null || _params$value2$ === void 0 ? void 0 : _params$value2$[pageSizeKey]) !== null && _params$value$0$pageS !== void 0 ? _params$value$0$pageS : finallyOptions.defaultParams[0][pageSizeKey] | ||
(_params$value$0$pageS = params.value?.[0]?.[pageSizeKey]) !== null && _params$value$0$pageS !== void 0 ? _params$value$0$pageS : finallyOptions.defaultParams[0][pageSizeKey] | ||
); | ||
@@ -1484,0 +1316,0 @@ }, |
@@ -25,3 +25,3 @@ import { WritableComputedRef, ComputedRef, Ref, WatchSource } from 'vue-demi'; | ||
declare type CacheData<R = any, P = any> = { | ||
type CacheData<R = any, P = any> = { | ||
data: R; | ||
@@ -31,10 +31,11 @@ params: P; | ||
}; | ||
declare const clearCache: (cacheKey?: string | undefined) => void; | ||
type CacheKey = string; | ||
declare const clearCache: (cacheKey?: CacheKey) => void; | ||
declare type MutateData<R> = (newData: R) => void; | ||
declare type MutateFunction<R> = (arg: (oldData: R) => R) => void; | ||
declare type Service<R, P extends unknown[]> = (...args: P) => Promise<R>; | ||
type MutateData<R> = (newData: R) => void; | ||
type MutateFunction<R> = (arg: (oldData: R) => R) => void; | ||
type Service<R, P extends unknown[]> = (...args: P) => Promise<R>; | ||
interface Mutate<R> extends MutateData<R>, MutateFunction<R> { | ||
} | ||
declare type State<R, P> = { | ||
type State<R, P> = { | ||
loading: Ref<boolean>; | ||
@@ -60,5 +61,5 @@ data: Ref<R | undefined>; | ||
} | ||
declare type ThrottleOptions = Omit<DebounceOptions, 'maxWait'>; | ||
declare type GlobalOptions = BaseOptions & PaginationExtendsOption; | ||
declare type BaseOptions = { | ||
type ThrottleOptions = Omit<DebounceOptions, 'maxWait'>; | ||
type GlobalOptions = BaseOptions & PaginationExtendsOption; | ||
type BaseOptions = { | ||
loadingDelay?: number | Ref<number>; | ||
@@ -83,7 +84,7 @@ loadingKeep?: number | Ref<number>; | ||
}; | ||
declare type Options<R, P extends unknown[]> = BaseOptions & { | ||
type Options<R, P extends unknown[]> = BaseOptions & { | ||
defaultParams?: P; | ||
ready?: Ref<boolean>; | ||
ready?: Ref<boolean> | (() => boolean); | ||
initialData?: R; | ||
refreshDeps?: WatchSource<any>[]; | ||
refreshDeps?: WatchSource | WatchSource[]; | ||
cacheKey?: string | ((params?: P) => string); | ||
@@ -99,8 +100,8 @@ refreshDepsAction?: () => void; | ||
declare type DataType = { | ||
type DataType = { | ||
list: any[]; | ||
[key: string]: any; | ||
}; | ||
declare type LoadMoreService<R extends DataType> = (data?: R) => Promise<R>; | ||
declare type LoadMoreBaseOptions<R> = Pick<Options<R, any>, 'ready' | 'manual' | 'refreshDeps' | 'refreshDepsAction' | 'debounceInterval' | 'debounceOptions' | 'throttleInterval' | 'throttleOptions' | 'errorRetryCount' | 'errorRetryInterval'> & { | ||
type LoadMoreService<R extends DataType> = (data?: R) => Promise<R>; | ||
type LoadMoreBaseOptions<R> = Pick<Options<R, any>, 'ready' | 'manual' | 'refreshDeps' | 'refreshDepsAction' | 'debounceInterval' | 'debounceOptions' | 'throttleInterval' | 'throttleOptions' | 'errorRetryCount' | 'errorRetryInterval'> & { | ||
isNoMore?: (data?: R) => boolean; | ||
@@ -112,3 +113,3 @@ onBefore?: () => void; | ||
}; | ||
declare type LoadMoreQueryResult<R extends DataType> = Pick<QueryResult<R, any>, 'data' | 'loading' | 'error' | 'refresh' | 'refreshAsync' | 'cancel' | 'mutate'> & { | ||
type LoadMoreQueryResult<R extends DataType> = Pick<QueryResult<R, any>, 'data' | 'loading' | 'error' | 'refresh' | 'refreshAsync' | 'cancel' | 'mutate'> & { | ||
dataList: ComputedRef<R['list']>; | ||
@@ -115,0 +116,0 @@ noMore: ComputedRef<boolean>; |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue-demi")):"function"==typeof define&&define.amd?define(["exports","vue-demi"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VueRequest=e.VueRequest||{},e.vueDemi)}(this,(function(e,t){"use strict";const n={},a=Symbol("GLOBAL_OPTIONS_PROVIDE_KEY"),r=()=>n,o=Object.prototype.toString,u=e=>"[object Object]"===(e=>o.call(e))(e),l=e=>Array.isArray(e),i=e=>null!==e&&"object"==typeof e,c=e=>e instanceof Function,s=e=>null==e,v="undefined"==typeof window,d=()=>{var e;return!(!v&&!s(null===(e=window.document)||void 0===e?void 0:e.visibilityState))||"visible"===window.document.visibilityState},f=()=>new Promise((()=>{})),m=(e,t,n)=>{const a=t.replace(/\[(\d+)\]/g,".$1").split(".");let r=e;for(const e of a)if(r=Object(r)[e],void 0===r)return n;return r};function p(e,t){const n=Object.assign({},e);for(const e of t)delete n[e];return n}const h=e=>t.isRef(e)?e.value:e,g=e=>i(e)?Object.assign(l(e)?[]:{},e):e,y=new Map;function w(e,t,n){let a,r,o,u,l,c,s=0,v=!1,d=!1,f=!0;const m=!t&&0!==t&&"function"==typeof window.requestAnimationFrame;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){const n=a,o=r;return a=r=void 0,s=t,u=e.apply(o,n),u}function h(e,t){return m?(window.cancelAnimationFrame(l),window.requestAnimationFrame(e)):setTimeout(e,t)}function g(e){const n=e-c;return void 0===c||n>=t||n<0||d&&e-s>=o}function y(){const e=Date.now();if(g(e))return w(e);l=h(y,function(e){const n=e-s,a=t-(e-c);return d?Math.min(a,o-n):a}(e))}function w(e){return l=void 0,f&&a?p(e):(a=r=void 0,u)}function E(...e){const n=Date.now(),o=g(n);if(a=e,r=this,c=n,o){if(void 0===l)return function(e){return s=e,l=h(y,t),v?p(e):u}(c);if(d)return l=h(y,t),p(c)}return void 0===l&&(l=h(y,t)),u}return t=+t||0,i(n)&&(v=!!n.leading,d="maxWait"in n,o=d?Math.max(+n.maxWait||0,t):o,f="trailing"in n?!!n.trailing:f),E.cancel=function(){void 0!==l&&function(e){if(m)return window.cancelAnimationFrame(e);clearTimeout(e)}(l),s=0,a=c=r=l=void 0},E.flush=function(){return void 0===l?u:w(Date.now())},E.pending=function(){return void 0!==l},E}function E(e,t){for(const n in t)void 0!==t[n]&&(i(t[n])&&i(e[n])&&n in e?(u(t[n])||l(t[n]))&&E(e[n],t[n]):e[n]=t[n])}function A(e,...t){const n=Object.assign({},e);if(!t.length)return n;for(const e of t)E(n,e);return n}var T=(e,{debounceInterval:n,debounceOptions:a,manual:r})=>{const o=t.ref(!1),u=t.ref(),l=t.computed((()=>a)),i=t.computed((()=>h(n))),c=t.ref(e.context.runAsync);return r||(o.value=!0),t.watchEffect((t=>{s(i.value)||(u.value=w((e=>e()),i.value,l.value),e.context.runAsync=(...e)=>new Promise(((t,n)=>{o.value?(o.value=!1,c.value(...e).then(t).catch(n)):u.value((()=>{c.value(...e).then(t).catch(n)}))})),t((()=>{var t;null===(t=u.value)||void 0===t||t.cancel(),e.context.runAsync=c.value})))})),{onCancel(){var e;null===(e=u.value)||void 0===e||e.cancel()}}},x=(e,{errorRetryCount:n=0,errorRetryInterval:a=0})=>{const r=t.ref(),o=t.ref(0),u=t.computed((()=>h(n))),l=t.computed((()=>h(a)));let i=!1;const c=()=>{o.value=0},s=t.computed((()=>{if(l.value)return l.value;return 1e3*Math.floor(Math.random()*2**Math.min(o.value,9)+1)})),v=()=>{r.value&&r.value()};return{onBefore(){i||c(),i=!1,v()},onSuccess(){c()},onError(){r.value=(()=>{let t;const n=-1===u.value,a=o.value<u.value;return(n||a)&&(n||(o.value+=1),t=setTimeout((()=>{i=!0,e.context.refresh()}),s.value)),()=>t&&clearTimeout(t)})()},onCancel(){c(),v()}}},S=(e,{ready:n=t.ref(!0),manual:a,defaultParams:r=[]})=>(t.watch(n,(t=>{!a&&t&&e.context.run(...r)}),{flush:"sync"}),{onBefore(){if(!n.value)return e.loading.value=!1,{isBreak:!0}}}),b=(e,{refreshDeps:n=[],refreshDepsAction:a,manual:r})=>(null!=n&&n.length&&t.watch(n,(()=>{a?a():!r&&e.context.refresh()})),{}),P=(e,{throttleInterval:n,throttleOptions:a})=>{const r=t.ref(),o=t.computed((()=>h(n))),u=t.computed((()=>a)),l=t.ref(e.context.runAsync);return t.watchEffect((t=>{if(s(n))return{};r.value=function(e,t,n){let a=!0,r=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return i(n)&&(a="leading"in n?!!n.leading:a,r="trailing"in n?!!n.trailing:r),w(e,t,{leading:a,trailing:r,maxWait:t})}((e=>e()),o.value,u.value),e.context.runAsync=(...e)=>new Promise(((t,n)=>{r.value((()=>{l.value(...e).then(t).catch(n)}))})),t((()=>{var t;null===(t=r.value)||void 0===t||t.cancel(),e.context.runAsync=l.value}))})),{onCancel(){var e;null===(e=r.value)||void 0===e||e.cancel()}}};const O=(e,n,a)=>{var r,o;const{initialData:u,onSuccess:l,onError:i,onBefore:s,onAfter:v}=n,d=t.ref(null!==(r=null==a?void 0:a.loading)&&void 0!==r&&r),m=t.shallowRef(null!==(o=null==a?void 0:a.data)&&void 0!==o?o:u),p=t.shallowRef(null==a?void 0:a.error),h=t.ref(null==a?void 0:a.params),y=t.ref([]),w=t.shallowRef("pending"),E={},A=(T={status:w,loading:d,data:m,error:p,params:h},x=[],e=>{Object.keys(e).forEach((t=>{T[t].value=e[t]})),x.forEach((e=>e(T)))});var T,x;const S=(e,...t)=>{if("onQuery"===e){const e=y.value.map((e=>e.onQuery)).filter(Boolean);return{servicePromise:(n=e,a=t[0],()=>{let e=a;for(let t=n.length;t-- >0;)e=n[t](e);return e()})()}}{const n=y.value.map((n=>{var a;return null===(a=n[e])||void 0===a?void 0:a.call(n,...t)}));return Object.assign({},...n)}var n,a},b=t.ref(0);return E.runAsync=async(...t)=>{A({loading:!0,params:t,status:"pending"}),b.value+=1;const n=b.value,{isBreak:a,breakResult:r=f()}=S("onBefore",t);if(a)return A({status:"settled"}),r;null==s||s(t);try{const a=()=>new Promise((t=>t(e(...h.value))));let{servicePromise:r}=S("onQuery",a);r||(r=a());const o=await r;return n!==b.value?f():(A({data:o,loading:!1,error:void 0,status:"settled"}),S("onSuccess",o,t),null==l||l(o,t),S("onAfter",t,o,void 0),null==v||v(t),o)}catch(e){if(n!==b.value)return f();throw A({loading:!1,error:e,status:"settled"}),S("onError",e,t),null==i||i(e,t),S("onAfter",t,void 0,e),null==v||v(t),e}},E.run=(...e)=>{E.runAsync(...e).catch((e=>{i||console.error(e)}))},E.cancel=()=>{b.value+=1,A({loading:!1}),S("onCancel")},E.refresh=()=>{E.run(...h.value||[])},E.refreshAsync=()=>E.runAsync(...h.value||[]),E.mutate=e=>{const t=c(e)?e(m.value):e,n=g(t);A({data:n}),S("onMutate",n)},{status:w,loading:d,data:m,error:p,params:h,plugins:y,context:E}};function R(e,n={},o){const u=t.inject(a,{}),l={...r(),...u,...n},{manual:i=!1,defaultParams:c=[]}=l,s=O(e,l);if(s.plugins.value=o.map((e=>e(s,l))),!i){const e=s.params.value||c;s.context.run(...e)}return t.onUnmounted((()=>{s.context.cancel()})),{loading:s.loading,data:s.data,error:s.error,params:s.params,cancel:s.context.cancel,refresh:s.context.refresh,refreshAsync:s.context.refreshAsync,mutate:s.context.mutate,run:s.context.run,runAsync:s.context.runAsync}}const M=new Map,j=new Map;var I=(e,{cacheKey:n,cacheTime:a=6e5,staleTime:r=0,getCache:o,setCache:u})=>{if(!n)return{};const l=c(n)?n:()=>n,i=t.ref((()=>{}));let v;const d=e=>o?o(e):(e=>{if(s(e))return;return y.get(e)})(e),f=(e,t,n)=>{u?u(e,n):((e,t,n)=>{const a=y.get(e);null!=a&&a.timer&&clearTimeout(a.timer);const r=setTimeout((()=>y.delete(e)),t);y.set(e,{...n,timer:r})})(e,t,n),((e,t)=>{j.has(e)&&j.get(e).forEach((e=>e(t)))})(e,n.data)},m=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),p=t=>{const n=l(t);return a=n,r=t=>{e.data.value=t},j.has(a)?j.get(a).push(r):j.set(a,[r]),()=>{const e=j.get(a).indexOf(r);j.get(a).splice(e,1)};var a,r},h=l(),g=d(h);return g&&m(g,"data")&&(e.data.value=g.data,e.params.value=g.params),h&&(i.value=p()),t.onUnmounted((()=>{i.value()})),{onBefore(t){const n=l(t),a=d(n);return a&&m(a,"data")?(o=a.time,-1===r||o+r>(new Date).getTime()?(e.data.value=a.data,e.loading.value=!1,{isBreak:!0,breakResult:a.data}):void(e.data.value=a.data)):{};var o},onQuery(t){const n=e.params.value,a=l(n);let r=(e=>M.get(e))(a);return r&&r!==v||(r=t(),v=r,((e,t)=>{M.set(e,t),t.then((t=>(M.delete(e),t))).catch((()=>{M.delete(e)}))})(a,r)),()=>r},onSuccess(e,t){const n=l(t);n&&(i.value(),f(n,a,{data:e,params:t,time:(new Date).getTime()}),i.value=p(t))},onMutate(t){const n=l(e.params.value);n&&(i.value(),f(n,a,{data:t,params:e.params.value,time:(new Date).getTime()}),i.value=p(e.params.value))}}};function L(){return(new Date).getTime()}var C,B=(e,{loadingDelay:n=0,loadingKeep:a=0})=>{const r=t.ref((()=>{})),o=t.computed((()=>h(n))),u=t.computed((()=>h(a)));let l=0,i={};return{onBefore(){e.loading.value=!o.value,r.value(),r.value=(()=>{let t;return o.value&&(t=setTimeout((()=>{"pending"===e.status.value&&(e.loading.value=!0)}),o.value)),()=>t&&clearTimeout(t)})(),l=L()},onQuery(e){if(!u.value)return()=>e();i=function(e){let t,n;return new class extends Promise{constructor(e){super(e),this.cancel=()=>{n(),clearTimeout(t)}}}((a=>{n=a,t=setTimeout(n,e)}))}(u.value+o.value);const t=Promise.allSettled([(async()=>{try{const t=await e();return L()-l<=o.value&&i.cancel(),Promise.resolve(t)}catch(e){return L()-l<=o.value&&i.cancel(),Promise.reject(e)}})(),i]).then((e=>{const t=e[0];return"fulfilled"===t.status?t.value:Promise.reject(t.reason)}));return()=>t},onCancel(){r.value()},onAfter(){r.value()}}};const D=new Set,N=new Set,_=new Set,K=(e,t)=>{let n;switch(e){case"FOCUS_LISTENER":n=D;break;case"RECONNECT_LISTENER":n=_;break;case"VISIBLE_LISTENER":n=N}if(!n.has(t))return n.add(t),()=>{n.delete(t)}},k=e=>{e.forEach((e=>{e()}))};!v&&null!==(C=window)&&void 0!==C&&C.addEventListener&&(window.addEventListener("visibilitychange",(()=>{d()&&k(N)}),!1),window.addEventListener("focus",(()=>k(D)),!1),window.addEventListener("online",(()=>k(_)),!1));var q=(e,{pollingInterval:n,pollingWhenHidden:a=!1,pollingWhenOffline:r=!1,errorRetryCount:o=0})=>{const u=t.ref(),l=t.ref(!1),i=t.computed((()=>h(n))),c=t.computed((()=>h(o))),f=[],m=e=>{e&&f.push(e)},p=()=>{return(a||d())&&(r||null===(e=!v&&(null===(t=window.navigator)||void 0===t?void 0:t.onLine))||void 0===e||e);var e,t},g=t=>{if(e.error.value&&0!==c.value)return;let n;if(!s(i.value)&&i.value>=0){if(!p())return void(l.value=!0);n=setTimeout(t,i.value)}return()=>n&&clearTimeout(n)},y=()=>{l.value&&p()&&(e.context.refresh(),l.value=!1)};return t.watch(i,(()=>{u.value&&(u.value(),u.value=g((()=>e.context.refresh())))})),a||m(K("VISIBLE_LISTENER",y)),r||m(K("RECONNECT_LISTENER",y)),t.onUnmounted((()=>{f.forEach((e=>e()))})),{onBefore(){var e;null===(e=u.value)||void 0===e||e.call(u)},onCancel(){var e;null===(e=u.value)||void 0===e||e.call(u)},onAfter(){u.value=g((()=>e.context.refresh()))}}};var F=(e,{refreshOnWindowFocus:n=!1,refocusTimespan:a=5e3})=>{const r=t.computed((()=>h(n))),o=t.computed((()=>h(a))),u=[],l=e=>{e&&u.push(e)},i=()=>{u.forEach((e=>e()))};return t.watchEffect((()=>{if(i(),r.value){const t=((e,t)=>{let n=!1;return(...a)=>{n||(n=!0,e(...a),setTimeout((()=>{n=!1}),t))}})(e.context.refresh,o.value);l(K("VISIBLE_LISTENER",t)),l(K("FOCUS_LISTENER",t))}})),t.onUnmounted((()=>{i()})),{}};function W(e,t){return R(e,t,[B,x,T,q,P,F,b,S,I])}e.clearCache=e=>{if(e){var t;const n=null===(t=y.get(e))||void 0===t?void 0:t.timer;n&&clearTimeout(n),y.delete(e)}else y.forEach((e=>e.timer&&clearTimeout(e.timer))),y.clear()},e.setGlobalOptions=e=>{Object.keys(e).forEach((t=>{n[t]=e[t]}))},e.useLoadMore=function(e,n){const{isNoMore:a,...r}=null!=n?n:{},o=t.shallowRef(),u=t.computed((()=>{var e;return(null===(e=o.value)||void 0===e?void 0:e.list)||[]})),l=t.ref(!1),i=t.ref(!1),s=t.ref(0),{runAsync:v,run:d,cancel:f,...m}=R((async t=>{const n=s.value,a=await e(t);return n===s.value&&(o.value=t?{...a,list:[...t.list,...a.list]}:a),a}),{...r,defaultParams:[],refreshDepsAction:()=>{null!=r&&r.refreshDepsAction?r.refreshDepsAction():w()},onError:e=>{var t;null==r||null===(t=r.onError)||void 0===t||t.call(r,e)},onSuccess:e=>{var t;null==r||null===(t=r.onSuccess)||void 0===t||t.call(r,e)},onBefore:()=>{var e;s.value+=1,i.value&&(i.value=!1,l.value=!0),null==r||null===(e=r.onBefore)||void 0===e||e.call(r)},onAfter:()=>{var e;l.value=!1,i.value=!1,null==r||null===(e=r.onAfter)||void 0===e||e.call(r)}},[x,T,P,b,S]),h=t.computed((()=>!(!a||!c(a))&&a(o.value))),y=()=>h.value?Promise.reject(((e,t=!1)=>{const n=`Warning: [vue-request] ${e}`;if(t)return new Error(n);console.error(n)})("No more data. You need to ignore this error by checking if `noMore` is false before calling `loadMoreAsync`",!0)):(i.value=!0,v(o.value)),w=()=>d();return{data:o,dataList:u,loadingMore:l,noMore:h,cancel:()=>{s.value+=1,f(),l.value=!1},mutate:e=>{const t=c(e)?e(o.value):e,n=g(t);o.value=n},refresh:w,refreshAsync:()=>v(),loadMore:()=>{y().catch((()=>{}))},loadMoreAsync:y,...p(m,["refresh","refreshAsync","mutate","params","data"])}},e.usePagination=function(e,n={}){const o=t.inject(a,{}),{pagination:u,...l}=n,{currentKey:i,pageSizeKey:c,totalKey:s,totalPageKey:v}=A({currentKey:"current",pageSizeKey:"pageSize",totalKey:"total",totalPageKey:"totalPage"},r().pagination||{},o.pagination||{},u||{}),d=A({defaultParams:[{[i]:1,[c]:10}]},l),{data:f,params:p,run:h,...g}=W(e,d),y=e=>{const[t,...n]=p.value||[],a=[{...t,...e},...n];h(...a)},w=e=>{y({[i]:e})},E=e=>{y({[c]:e})},T=t.computed((()=>m(f.value,s,0))),x=t.computed({get:()=>{var e,t,n;return null!==(e=null===(t=p.value)||void 0===t||null===(n=t[0])||void 0===n?void 0:n[i])&&void 0!==e?e:d.defaultParams[0][i]},set:e=>{w(e)}}),S=t.computed({get:()=>{var e,t,n;return null!==(e=null===(t=p.value)||void 0===t||null===(n=t[0])||void 0===n?void 0:n[c])&&void 0!==e?e:d.defaultParams[0][c]},set:e=>{E(e)}}),b=t.computed((()=>m(f.value,v,Math.ceil(T.value/S.value))));return{data:f,params:p,current:x,pageSize:S,total:T,totalPage:b,run:h,changeCurrent:w,changePageSize:E,changePagination:(e,t)=>{y({[i]:e,[c]:t})},...g}},e.useRequest=W,e.useRequestProvider=e=>{t.provide(a,e)},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue-demi")):"function"==typeof define&&define.amd?define(["exports","vue-demi"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VueRequest=e.VueRequest||{},e.vueDemi)}(this,(function(e,t){"use strict";const n={},r=Symbol("GLOBAL_OPTIONS_PROVIDE_KEY"),a=()=>n,o=Object.prototype.toString,u=e=>"[object Object]"===(e=>o.call(e))(e),l=e=>Array.isArray(e),c=e=>null!==e&&"object"==typeof e,i=e=>e instanceof Function,s=e=>null==e,v="undefined"==typeof window,f=()=>!(!v&&!s(window.document?.visibilityState))||"visible"===window.document.visibilityState,d=()=>new Promise((()=>{})),m=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;const r=t.replace(/\[(\d+)\]/g,".$1").split(".");let a=e;for(const e of r)if(a=Object(a)[e],void 0===a)return n;return a};function h(e,t){const n=Object.assign({},e);for(const e of t)delete n[e];return n}const p=e=>t.isRef(e)?e.value:e,g=e=>c(e)?Object.assign(l(e)?[]:{},e):e,y=new Map;function w(e,t,n){let r,a,o,u,l,i,s=0,v=!1,f=!1,d=!0;const m=!t&&0!==t&&"function"==typeof window.requestAnimationFrame;if("function"!=typeof e)throw new TypeError("Expected a function");function h(t){const n=r,o=a;return r=a=void 0,s=t,u=e.apply(o,n),u}function p(e,t){return m?(window.cancelAnimationFrame(l),window.requestAnimationFrame(e)):setTimeout(e,t)}function g(e){const n=e-i;return void 0===i||n>=t||n<0||f&&e-s>=o}function y(){const e=Date.now();if(g(e))return w(e);l=p(y,function(e){const n=e-s,r=t-(e-i);return f?Math.min(r,o-n):r}(e))}function w(e){return l=void 0,d&&r?h(e):(r=a=void 0,u)}function E(){const e=Date.now(),n=g(e);for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];if(r=c,a=this,i=e,n){if(void 0===l)return function(e){return s=e,l=p(y,t),v?h(e):u}(i);if(f)return l=p(y,t),h(i)}return void 0===l&&(l=p(y,t)),u}return t=+t||0,c(n)&&(v=!!n.leading,f="maxWait"in n,o=f?Math.max(+n.maxWait||0,t):o,d="trailing"in n?!!n.trailing:d),E.cancel=function(){void 0!==l&&function(e){if(m)return window.cancelAnimationFrame(e);clearTimeout(e)}(l),s=0,r=i=a=l=void 0},E.flush=function(){return void 0===l?u:w(Date.now())},E.pending=function(){return void 0!==l},E}function E(e,t){for(const n in t)void 0!==t[n]&&(c(t[n])&&c(e[n])&&n in e?(u(t[n])||l(t[n]))&&E(e[n],t[n]):e[n]=t[n])}function A(e){const t=Object.assign({},e);for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];if(!r.length)return t;for(const e of r)E(t,e);return t}var T=(e,n)=>{let{debounceInterval:r,debounceOptions:a,manual:o}=n;const u=t.ref(!1),l=t.ref(),c=t.computed((()=>a)),i=t.computed((()=>p(r))),v=t.ref(e.context.runAsync);return o||(u.value=!0),t.watchEffect((t=>{s(i.value)||(l.value=w((e=>e()),i.value,c.value),e.context.runAsync=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Promise(((e,n)=>{u.value?(u.value=!1,v.value(...t).then(e).catch(n)):l.value((()=>{v.value(...t).then(e).catch(n)}))}))},t((()=>{l.value?.cancel(),e.context.runAsync=v.value})))})),{onCancel(){l.value?.cancel()}}},x=(e,n)=>{let{errorRetryCount:r=0,errorRetryInterval:a=0}=n;const o=t.ref(),u=t.ref(0),l=t.computed((()=>p(r))),c=t.computed((()=>p(a)));let i=!1;const s=()=>{u.value=0},v=t.computed((()=>{if(c.value)return c.value;return 1e3*Math.floor(Math.random()*2**Math.min(u.value,9)+1)})),f=()=>{o.value&&o.value()};return{onBefore(){i||s(),i=!1,f()},onSuccess(){s()},onError(){o.value=(()=>{let t;const n=-1===l.value,r=u.value<l.value;return(n||r)&&(n||(u.value+=1),t=setTimeout((()=>{i=!0,e.context.refresh()}),v.value)),()=>t&&clearTimeout(t)})()},onCancel(){s(),f()}}},S=(e,n)=>{let{ready:r=t.ref(!0),manual:a,defaultParams:o=[]}=n;return t.watch(r,(t=>{!a&&t&&e.context.run(...o)}),{flush:"sync"}),{onBefore(){if(!(i(r)?r():r.value))return e.loading.value=!1,{isBreak:!0}}}},b=(e,n)=>{let{refreshDeps:r,refreshDepsAction:a,manual:o}=n;if(void 0===r||l(r)&&0===r.length)return{};const u=l(r)?r:[r];return t.watch(u,(()=>{a?a():!o&&e.context.refresh()})),{}},P=(e,n)=>{let{throttleInterval:r,throttleOptions:a}=n;const o=t.ref(),u=t.computed((()=>p(r))),l=t.computed((()=>a)),i=t.ref(e.context.runAsync);return t.watchEffect((t=>{if(s(r))return{};o.value=function(e,t,n){let r=!0,a=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return c(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),w(e,t,{leading:r,trailing:a,maxWait:t})}((e=>e()),u.value,l.value),e.context.runAsync=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Promise(((e,n)=>{o.value((()=>{i.value(...t).then(e).catch(n)}))}))},t((()=>{o.value?.cancel(),e.context.runAsync=i.value}))})),{onCancel(){o.value?.cancel()}}};const O=(e,n,r)=>{var a,o;const{initialData:u,onSuccess:l,onError:c,onBefore:s,onAfter:v}=n,f=t.ref(null!==(a=r?.loading)&&void 0!==a&&a),m=t.shallowRef(null!==(o=r?.data)&&void 0!==o?o:u),h=t.shallowRef(r?.error),p=t.ref(r?.params),y=t.ref([]),w=t.shallowRef("pending"),E={},A=(T={status:w,loading:f,data:m,error:h,params:p},x=[],e=>{Object.keys(e).forEach((t=>{T[t].value=e[t]})),x.forEach((e=>e(T)))});var T,x;const S=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if("onQuery"===e){const e=y.value.map((e=>e.onQuery)).filter(Boolean);return{servicePromise:(a=e,o=n[0],()=>{let e=o;for(let t=a.length;t-- >0;)e=a[t](e);return e()})()}}{const t=y.value.map((t=>t[e]?.(...n)));return Object.assign({},...t)}var a,o},b=t.ref(0);return E.runAsync=async function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];A({loading:!0,params:n,status:"pending"}),b.value+=1;const a=b.value,{isBreak:o,breakResult:u=d()}=S("onBefore",n);if(o)return A({status:"settled"}),u;s?.(n);try{const t=()=>new Promise((t=>t(e(...p.value))));let{servicePromise:r}=S("onQuery",t);r||(r=t());const o=await r;return a!==b.value?d():(A({data:o,loading:!1,error:void 0,status:"settled"}),S("onSuccess",o,n),l?.(o,n),a===b.value&&S("onAfter",n,o,void 0),v?.(n),o)}catch(e){if(a!==b.value)return d();throw A({loading:!1,error:e,status:"settled"}),S("onError",e,n),c?.(e,n),a===b.value&&S("onAfter",n,void 0,e),v?.(n),e}},E.run=function(){E.runAsync(...arguments).catch((e=>{c||console.error(e)}))},E.cancel=()=>{b.value+=1,A({loading:!1}),S("onCancel")},E.refresh=()=>{E.run(...p.value||[])},E.refreshAsync=()=>E.runAsync(...p.value||[]),E.mutate=e=>{const t=i(e)?e(m.value):e,n=g(t);A({data:n}),S("onMutate",n)},{status:w,loading:f,data:m,error:h,params:p,plugins:y,context:E}};function R(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2?arguments[2]:void 0;const u=t.inject(r,{}),l={...a(),...u,...n},{manual:c=!1,defaultParams:i=[]}=l,s=O(e,l);if(s.plugins.value=o.map((e=>e(s,l))),!c){const e=s.params.value||i;s.context.run(...e)}return t.onUnmounted((()=>{s.context.cancel()})),{loading:s.loading,data:s.data,error:s.error,params:s.params,cancel:s.context.cancel,refresh:s.context.refresh,refreshAsync:s.context.refreshAsync,mutate:s.context.mutate,run:s.context.run,runAsync:s.context.runAsync}}const M=new Map,j=new Map;var I=(e,n)=>{let{cacheKey:r,cacheTime:a=6e5,staleTime:o=0,getCache:u,setCache:l}=n;if(!r)return{};const c=i(r)?r:()=>r,v=t.ref((()=>{}));let f;const d=e=>u?u(e):(e=>{if(s(e))return;return y.get(e)})(e),m=(e,t,n)=>{l?l(e,n):((e,t,n)=>{const r=y.get(e);r?.timer&&clearTimeout(r.timer);const a=setTimeout((()=>y.delete(e)),t);y.set(e,{...n,timer:a})})(e,t,n),((e,t)=>{j.has(e)&&j.get(e).forEach((e=>e(t)))})(e,n.data)},h=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),p=t=>{const n=c(t);return r=n,a=t=>{e.data.value=t},j.has(r)?j.get(r).push(a):j.set(r,[a]),()=>{const e=j.get(r).indexOf(a);j.get(r).splice(e,1)};var r,a},g=c(),w=d(g);return w&&h(w,"data")&&(e.data.value=w.data,e.params.value=w.params),g&&(v.value=p()),t.onUnmounted((()=>{v.value()})),{onBefore(t){const n=c(t),r=d(n);return r&&h(r,"data")?(a=r.time,-1===o||a+o>(new Date).getTime()?(e.data.value=r.data,e.loading.value=!1,{isBreak:!0,breakResult:r.data}):void(e.data.value=r.data)):{};var a},onQuery(t){const n=e.params.value,r=c(n);let a=(e=>M.get(e))(r);return a&&a!==f||(a=t(),f=a,((e,t)=>{M.set(e,t),t.then((t=>(M.delete(e),t))).catch((()=>{M.delete(e)}))})(r,a)),()=>a},onSuccess(e,t){const n=c(t);n&&(v.value(),m(n,a,{data:e,params:t,time:(new Date).getTime()}),v.value=p(t))},onMutate(t){const n=c(e.params.value);n&&(v.value(),m(n,a,{data:t,params:e.params.value,time:(new Date).getTime()}),v.value=p(e.params.value))}}};function L(){return(new Date).getTime()}var C=(e,n)=>{let{loadingDelay:r=0,loadingKeep:a=0}=n;const o=t.ref((()=>{})),u=t.computed((()=>p(r))),l=t.computed((()=>p(a)));let c=0,i={};return{onBefore(){e.loading.value=!u.value,o.value(),o.value=(()=>{let t;return u.value&&(t=setTimeout((()=>{"pending"===e.status.value&&(e.loading.value=!0)}),u.value)),()=>t&&clearTimeout(t)})(),c=L()},onQuery(e){if(!l.value)return()=>e();i=function(e){let t,n;return new class extends Promise{constructor(e){super(e),this.cancel=()=>{n(),clearTimeout(t)}}}((r=>{n=r,t=setTimeout(n,e)}))}(l.value+u.value);const t=Promise.allSettled([(async()=>{try{const t=await e();return L()-c<=u.value&&i.cancel(),Promise.resolve(t)}catch(e){return L()-c<=u.value&&i.cancel(),Promise.reject(e)}})(),i]).then((e=>{const t=e[0];return"fulfilled"===t.status?t.value:Promise.reject(t.reason)}));return()=>t},onCancel(){o.value()},onAfter(){o.value()}}};const B=new Set,D=new Set,N=new Set,_=(e,t)=>{let n;switch(e){case"FOCUS_LISTENER":n=B;break;case"RECONNECT_LISTENER":n=N;break;case"VISIBLE_LISTENER":n=D}if(!n.has(t))return n.add(t),()=>{n.delete(t)}},K=e=>{e.forEach((e=>{e()}))};!v&&window?.addEventListener&&(window.addEventListener("visibilitychange",(()=>{f()&&K(D)}),!1),window.addEventListener("focus",(()=>K(B)),!1),window.addEventListener("online",(()=>K(N)),!1));var k=(e,n)=>{let{pollingInterval:r,pollingWhenHidden:a=!1,pollingWhenOffline:o=!1,errorRetryCount:u=0}=n;const l=t.ref(),c=t.ref(!1),i=t.computed((()=>p(r))),d=t.computed((()=>p(u))),m=[],h=e=>{e&&m.push(e)},g=()=>(a||f())&&(o||(()=>{var e;return null===(e=!v&&window.navigator?.onLine)||void 0===e||e})()),y=t=>{if(e.error.value&&0!==d.value)return;let n;if(!s(i.value)&&i.value>=0){if(!g())return void(c.value=!0);n=setTimeout(t,i.value)}return()=>n&&clearTimeout(n)},w=()=>{c.value&&g()&&(e.context.refresh(),c.value=!1)};return t.watch(i,(()=>{l.value&&(l.value(),l.value=y((()=>e.context.refresh())))})),a||h(_("VISIBLE_LISTENER",w)),o||h(_("RECONNECT_LISTENER",w)),t.onUnmounted((()=>{m.forEach((e=>e()))})),{onBefore(){l.value?.()},onCancel(){l.value?.()},onAfter(){l.value=y((()=>e.context.refresh()))}}};var q=(e,n)=>{let{refreshOnWindowFocus:r=!1,refocusTimespan:a=5e3}=n;const o=t.computed((()=>p(r))),u=t.computed((()=>p(a))),l=[],c=e=>{e&&l.push(e)},i=()=>{l.forEach((e=>e()))};return t.watchEffect((()=>{if(i(),o.value){const t=((e,t)=>{let n=!1;return function(){n||(n=!0,e(...arguments),setTimeout((()=>{n=!1}),t))}})(e.context.refresh,u.value);c(_("VISIBLE_LISTENER",t)),c(_("FOCUS_LISTENER",t))}})),t.onUnmounted((()=>{i()})),{}};function F(e,t){return R(e,t,[C,x,T,k,P,q,b,S,I])}e.clearCache=e=>{if(e){const t=y.get(e)?.timer;t&&clearTimeout(t),y.delete(e)}else y.forEach((e=>e.timer&&clearTimeout(e.timer))),y.clear()},e.setGlobalOptions=e=>{Object.keys(e).forEach((t=>{n[t]=e[t]}))},e.useLoadMore=function(e,n){const{isNoMore:r,...a}=null!=n?n:{},o=t.shallowRef(),u=t.computed((()=>o.value?.list||[])),l=t.ref(!1),c=t.ref(!1),s=t.ref(0),{runAsync:v,run:f,cancel:d,...m}=R((async t=>{const n=s.value,r=await e(t);return n===s.value&&(o.value=t?{...r,list:[...t.list,...r.list]}:r),r}),{...a,defaultParams:[],refreshDepsAction:()=>{a?.refreshDepsAction?a.refreshDepsAction():w()},onError:e=>{a?.onError?.(e)},onSuccess:e=>{a?.onSuccess?.(e)},onBefore:()=>{s.value+=1,c.value&&(c.value=!1,l.value=!0),a?.onBefore?.()},onAfter:()=>{l.value=!1,c.value=!1,a?.onAfter?.()}},[x,T,P,b,S]),p=t.computed((()=>!(!r||!i(r))&&r(o.value))),y=()=>p.value?Promise.reject(function(e){const t=`Warning: [vue-request] ${e}`;if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])return new Error(t);console.error(t)}("No more data. You need to ignore this error by checking if `noMore` is false before calling `loadMoreAsync`",!0)):(c.value=!0,v(o.value)),w=()=>f();return{data:o,dataList:u,loadingMore:l,noMore:p,cancel:()=>{s.value+=1,d(),l.value=!1},mutate:e=>{const t=i(e)?e(o.value):e,n=g(t);o.value=n},refresh:w,refreshAsync:()=>v(),loadMore:()=>{y().catch((()=>{}))},loadMoreAsync:y,...h(m,["refresh","refreshAsync","mutate","params","data"])}},e.usePagination=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=t.inject(r,{}),{pagination:u,...l}=n,{currentKey:c,pageSizeKey:i,totalKey:s,totalPageKey:v}=A({currentKey:"current",pageSizeKey:"pageSize",totalKey:"total",totalPageKey:"totalPage"},a().pagination||{},o.pagination||{},u||{}),f=A({defaultParams:[{[c]:1,[i]:10}]},l),{data:d,params:h,run:p,...g}=F(e,f),y=e=>{const[t,...n]=h.value||[],r=[{...t,...e},...n];p(...r)},w=e=>{y({[c]:e})},E=e=>{y({[i]:e})},T=t.computed((()=>m(d.value,s,0))),x=t.computed({get:()=>{var e;return null!==(e=h.value?.[0]?.[c])&&void 0!==e?e:f.defaultParams[0][c]},set:e=>{w(e)}}),S=t.computed({get:()=>{var e;return null!==(e=h.value?.[0]?.[i])&&void 0!==e?e:f.defaultParams[0][i]},set:e=>{E(e)}}),b=t.computed((()=>m(d.value,v,Math.ceil(T.value/S.value))));return{data:d,params:h,current:x,pageSize:S,total:T,totalPage:b,run:p,changeCurrent:w,changePageSize:E,changePagination:(e,t)=>{y({[c]:e,[i]:t})},...g}},e.useRequest=F,e.useRequestProvider=e=>{t.provide(r,e)},Object.defineProperty(e,"__esModule",{value:!0})})); |
{ | ||
"name": "vue-request", | ||
"version": "2.0.0-rc.4", | ||
"version": "2.0.0", | ||
"description": "Vue composition API for data fetching, supports SWR, polling, error retry, cache request, pagination and other cool features.", | ||
@@ -37,16 +37,16 @@ "keywords": [ | ||
"build:types": "rollup --config ./build/rollup.config.types.js", | ||
"changelog": "standard-version && standard-version -i CHANGELOG.zh-CN.md -o CHANGELOG.zh-CN.md", | ||
"clean": "rimraf dist/*", | ||
"dev": "yarn switch:3 && vite --config ./build/vite.config.ts ./examples/vue3", | ||
"dev:2": "yarn switch:2 && vite --config ./build/vite-vue2.config.ts ./examples/vue2", | ||
"format": "prettier -w '**/*.ts?(x)'", | ||
"lint": "eslint -c ./.eslintrc.js './{src,scripts,build}/**/*.{js,ts,tsx}'", | ||
"patch-package": "patch-package", | ||
"publishing": "np", | ||
"release": "yarn build && yarn publishing", | ||
"switch:2": "vue-demi-switch 2.7 vue2", | ||
"switch:3": "vue-demi-switch 3", | ||
"test": "yarn test:3 && yarn test:2", | ||
"test:3": "yarn switch:3 && jest --coverage", | ||
"test:2": "yarn switch:2 && jest --coverage", | ||
"switch:3": "vue-demi-switch 3 vue3", | ||
"switch:2": "vue-demi-switch 2 vue2", | ||
"clean": "rimraf dist/*", | ||
"publishing": "np", | ||
"changelog": "standard-version && standard-version -i CHANGELOG.zh-CN.md -o CHANGELOG.zh-CN.md", | ||
"release": "yarn build && yarn publishing", | ||
"lint": "eslint -c ./.eslintrc.js './{src,scripts,build}/**/*.{js,ts,tsx}'", | ||
"format": "prettier -w '**/*.ts?(x)'", | ||
"patch-package": "patch-package" | ||
"test:3": "yarn switch:3 && jest --coverage" | ||
}, | ||
@@ -113,5 +113,5 @@ "lint-staged": { | ||
"vite-plugin-vue2": "^1.9.2", | ||
"vue": "^3.3.4", | ||
"vue-template-compiler": "^2.6.14", | ||
"vue2": "npm:vue@2", | ||
"vue3": "npm:vue@3" | ||
"vue2": "npm:vue@2" | ||
}, | ||
@@ -118,0 +118,0 @@ "peerDependencies": { |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
2615
1
125341