norm-axios
Version:
Norm Axios 是一个基于 Axios 的约定式请求库,提供了约定式的请求方式与强大的 Hook API,帮助你更高效的开发。
892 lines (891 loc) • 32.6 kB
JavaScript
;
var __webpack_require__ = {};
(()=>{
__webpack_require__.n = (module)=>{
var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
__webpack_require__.d(getter, {
a: getter
});
return getter;
};
})();
(()=>{
__webpack_require__.d = (exports1, definition)=>{
for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
enumerable: true,
get: definition[key]
});
};
})();
(()=>{
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
__webpack_require__.r = (exports1)=>{
if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
value: 'Module'
});
Object.defineProperty(exports1, '__esModule', {
value: true
});
};
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
definePlugin: ()=>define_plugin,
GLOBAL_CONFIG_PROVIDER_SYMBOL: ()=>GLOBAL_CONFIG_PROVIDER_SYMBOL,
clearCache: ()=>clearCache,
getCacheAll: ()=>getCacheAll,
usePagination: ()=>usePagination,
NormAxios: ()=>NormAxios,
useRequest: ()=>useRequest,
useGlobalConfigProvider: ()=>useGlobalConfigProvider
});
const external_axios_namespaceObject = require("axios");
var external_axios_default = /*#__PURE__*/ __webpack_require__.n(external_axios_namespaceObject);
function omit(obj, keys) {
const result = {
...obj
};
for(let i = 0; i < keys.length; i++){
const key = keys[i];
delete result[key];
}
return result;
}
class NormAxios {
axiosInstance;
axiosConfig;
constructor(config){
this.axiosInstance = external_axios_default().create(omit(config, [
'interceptor'
]));
this.axiosConfig = config;
this.axiosInstance.interceptors.request.use(async (requestConfig)=>{
await config.interceptor?.onBeforeRequest?.(requestConfig);
return requestConfig;
}, (error)=>Promise.reject(error));
this.axiosInstance.interceptors.response.use((response)=>config.interceptor?.onResponse?.(response) || response, (error)=>config?.interceptor?.onResponseError?.(error));
}
request(config) {
return this.axiosInstance.request(config);
}
get(url, params, config) {
return this.request({
method: 'get',
url,
params,
...config
});
}
post(url, data, config) {
return this.request({
method: 'post',
url,
data,
...config
});
}
put(url, data, config) {
return this.request({
method: 'put',
url,
data,
...config
});
}
delete(url, data, config) {
return this.request({
method: 'delete',
url,
data,
...config
});
}
static extend(instance, config) {
return new NormAxios(Object.assign(instance.axiosConfig, config));
}
}
function definePlugin(options) {
return options;
}
const define_plugin = definePlugin;
const CACHE_STORE = new Map();
const getCache = (cacheKey)=>CACHE_STORE.get(cacheKey);
const setCache = (cacheKey, cacheTime, cacheData)=>{
const cache = getCache(cacheKey);
if (cache?.timer) clearTimeout(cache.timer);
const timer = setTimeout(()=>CACHE_STORE.delete(cacheKey), cacheTime);
CACHE_STORE.set(cacheKey, {
...cacheData,
timer
});
};
const getCacheAll = ()=>Object.fromEntries(CACHE_STORE.entries());
const clearCache = (key)=>{
if (!key) return CACHE_STORE.clear();
const cacheKeys = Array.isArray(key) ? key : [
key
];
cacheKeys.forEach((cacheKey)=>CACHE_STORE.delete(cacheKey));
};
function debounce_debounce(func, debounceMs, { signal, edges } = {}) {
let pendingThis;
let pendingArgs = null;
const leading = null != edges && edges.includes('leading');
const trailing = null == edges || edges.includes('trailing');
const invoke = ()=>{
if (null !== pendingArgs) {
func.apply(pendingThis, pendingArgs);
pendingThis = void 0;
pendingArgs = null;
}
};
const onTimerEnd = ()=>{
if (trailing) invoke();
cancel();
};
let timeoutId = null;
const schedule = ()=>{
if (null != timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(()=>{
timeoutId = null;
onTimerEnd();
}, debounceMs);
};
const cancelTimer = ()=>{
if (null !== timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
const cancel = ()=>{
cancelTimer();
pendingThis = void 0;
pendingArgs = null;
};
const flush = ()=>{
cancelTimer();
invoke();
};
const debounced = function(...args) {
if (signal?.aborted) return;
pendingThis = this;
pendingArgs = args;
const isFirstCall = null == timeoutId;
schedule();
if (leading && isFirstCall) invoke();
};
debounced.schedule = schedule;
debounced.cancel = cancel;
debounced.flush = flush;
signal?.addEventListener('abort', cancel, {
once: true
});
return debounced;
}
function function_debounce_debounce(func, debounceMs = 0, options = {}) {
if ('object' != typeof options) options = {};
const { signal, leading = false, trailing = true, maxWait } = options;
const edges = Array(2);
if (leading) edges[0] = 'leading';
if (trailing) edges[1] = 'trailing';
let result;
let pendingAt = null;
const _debounced = debounce_debounce(function(...args) {
result = func.apply(this, args);
pendingAt = null;
}, debounceMs, {
signal,
edges
});
const debounced = function(...args) {
if (null != maxWait) {
if (null === pendingAt) pendingAt = Date.now();
else if (Date.now() - pendingAt >= maxWait) {
result = func.apply(this, args);
pendingAt = Date.now();
_debounced.cancel();
_debounced.schedule();
return result;
}
}
_debounced.apply(this, args);
return result;
};
const flush = ()=>{
_debounced.flush();
return result;
};
debounced.cancel = _debounced.cancel;
debounced.flush = flush;
return debounced;
}
const external_vue_namespaceObject = require("vue");
function useDebounce(fn, ms, options) {
const createDebounceFn = ()=>function_debounce_debounce(fn, (0, external_vue_namespaceObject.toValue)(ms), {
leading: (0, external_vue_namespaceObject.toValue)(options.leading),
trailing: (0, external_vue_namespaceObject.toValue)(options.trailing),
maxWait: (0, external_vue_namespaceObject.toValue)(options.maxWait)
});
let debounceFn = createDebounceFn();
(0, external_vue_namespaceObject.watchEffect)(()=>{
if (debounceFn) debounceFn.cancel();
debounceFn = createDebounceFn();
});
return debounceFn;
}
const hooks_debounce = useDebounce;
const GLOBAL_CONFIG_PROVIDER_SYMBOL = Symbol('GlobalProvider');
function useGlobalConfigProvider(config) {
(0, external_vue_namespaceObject.provide)(GLOBAL_CONFIG_PROVIDER_SYMBOL, config);
}
function shared_tryOnScopeDispose(fn) {
if ((0, external_vue_namespaceObject.getCurrentScope)()) {
(0, external_vue_namespaceObject.onScopeDispose)(fn);
return true;
}
return false;
}
const shared_isClient = "undefined" != typeof window && "undefined" != typeof document;
const shared_toString = Object.prototype.toString;
const shared_isObject = (val)=>"[object Object]" === shared_toString.call(val);
function cacheStringFunction(fn) {
const cache = /* @__PURE__ */ Object.create(null);
return (str)=>{
const hit = cache[str];
return hit || (cache[str] = fn(str));
};
}
const hyphenateRE = /\B([A-Z])/g;
cacheStringFunction((str)=>str.replace(hyphenateRE, "-$1").toLowerCase());
const camelizeRE = /-(\w)/g;
cacheStringFunction((str)=>str.replace(camelizeRE, (_, c)=>c ? c.toUpperCase() : ""));
function shared_toArray(value) {
return Array.isArray(value) ? value : [
value
];
}
function shared_watchImmediate(source, cb, options) {
return (0, external_vue_namespaceObject.watch)(source, cb, {
...options,
immediate: true
});
}
const defaultWindow = shared_isClient ? window : void 0;
const defaultDocument = shared_isClient ? window.document : void 0;
shared_isClient && window.navigator;
shared_isClient && window.location;
function unrefElement(elRef) {
var _a;
const plain = (0, external_vue_namespaceObject.toValue)(elRef);
return null != (_a = null == plain ? void 0 : plain.$el) ? _a : plain;
}
function useEventListener(...args) {
const cleanups = [];
const cleanup = ()=>{
cleanups.forEach((fn)=>fn());
cleanups.length = 0;
};
const register = (el, event, listener, options)=>{
el.addEventListener(event, listener, options);
return ()=>el.removeEventListener(event, listener, options);
};
const firstParamTargets = (0, external_vue_namespaceObject.computed)(()=>{
const test = shared_toArray((0, external_vue_namespaceObject.toValue)(args[0])).filter((e)=>null != e);
return test.every((e)=>"string" != typeof e) ? test : void 0;
});
const stopWatch = shared_watchImmediate(()=>{
var _a, _b;
return [
null != (_b = null == (_a = firstParamTargets.value) ? void 0 : _a.map((e)=>unrefElement(e))) ? _b : [
defaultWindow
].filter((e)=>null != e),
shared_toArray((0, external_vue_namespaceObject.toValue)(firstParamTargets.value ? args[1] : args[0])),
shared_toArray((0, external_vue_namespaceObject.unref)(firstParamTargets.value ? args[2] : args[1])),
(0, external_vue_namespaceObject.toValue)(firstParamTargets.value ? args[3] : args[2])
];
}, ([raw_targets, raw_events, raw_listeners, raw_options])=>{
cleanup();
if (!(null == raw_targets ? void 0 : raw_targets.length) || !(null == raw_events ? void 0 : raw_events.length) || !(null == raw_listeners ? void 0 : raw_listeners.length)) return;
const optionsClone = shared_isObject(raw_options) ? {
...raw_options
} : raw_options;
cleanups.push(...raw_targets.flatMap((el)=>raw_events.flatMap((event)=>raw_listeners.map((listener)=>register(el, event, listener, optionsClone)))));
}, {
flush: "post"
});
const stop = ()=>{
stopWatch();
cleanup();
};
shared_tryOnScopeDispose(cleanup);
return stop;
}
Symbol("vueuse-ssr-width");
"undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self && self;
function useDocumentVisibility(options = {}) {
const { document: document1 = defaultDocument } = options;
if (!document1) return (0, external_vue_namespaceObject.shallowRef)("visible");
const visibility = (0, external_vue_namespaceObject.shallowRef)(document1.visibilityState);
useEventListener(document1, "visibilitychange", ()=>{
visibility.value = document1.visibilityState;
}, {
passive: true
});
return visibility;
}
function useWindowFocus(options = {}) {
const { window: window1 = defaultWindow } = options;
if (!window1) return (0, external_vue_namespaceObject.shallowRef)(false);
const focused = (0, external_vue_namespaceObject.shallowRef)(window1.document.hasFocus());
const listenerOptions = {
passive: true
};
useEventListener(window1, "blur", ()=>{
focused.value = false;
}, listenerOptions);
useEventListener(window1, "focus", ()=>{
focused.value = true;
}, listenerOptions);
return focused;
}
function isBoolean(x) {
return 'boolean' == typeof x;
}
function isFunction(value) {
return 'function' == typeof value;
}
function throttle_throttle(func, throttleMs = 0, options = {}) {
if ('object' != typeof options) options = {};
const { leading = true, trailing = true, signal } = options;
return function_debounce_debounce(func, throttleMs, {
leading,
trailing,
signal,
maxWait: throttleMs
});
}
function useThrottle(fn, ms, options) {
const createThrottle = ()=>throttle_throttle(fn, (0, external_vue_namespaceObject.toValue)(ms), {
leading: (0, external_vue_namespaceObject.toValue)(options.leading),
trailing: (0, external_vue_namespaceObject.toValue)(options.trailing)
});
let throttleFn = createThrottle();
(0, external_vue_namespaceObject.watchEffect)(()=>{
if (throttleFn) throttleFn.cancel();
throttleFn = createThrottle();
});
return throttleFn;
}
const hooks_throttle = useThrottle;
function useCoreRequest({ setState, rawState, data }, service, options = {}, runPluginHooks) {
const { ready = (0, external_vue_namespaceObject.ref)(true), debounceWait = 500, debounceMaxWait, debounceLeading = false, debounceTrailing = true, throttleWait = 500, throttleLeading = true, throttleTrailing = true, onBefore, onFinally, onError, onSuccess, onFinallyFetchDone, formatData } = options;
let count = 0;
let isCancelled = false;
const coreRequest = async (...args)=>{
setTimeout(()=>{
onBefore?.(args);
}, 0);
const beforeReturn = runPluginHooks('onBefore', args);
if (beforeReturn?.isReturned) {
setState({
loading: false,
finished: true
});
return;
}
count += 1;
const currentCount = count;
setState({
params: args,
finished: false
});
try {
const serviceWrapper = (...params)=>new Promise((resolve)=>resolve(service(...params)));
const { servicePromise } = runPluginHooks('onRequest', serviceWrapper, args);
const content = await (servicePromise || serviceWrapper(...args));
if (!Array.isArray(content)) return Promise.reject(new TypeError('server 请返回正确的 ResponseContent 类型格式'));
const [result, err, res] = content;
if (currentCount === count) {
setState({
finished: true
});
onFinallyFetchDone?.(args);
runPluginHooks('onFinallyFetchDone', args);
}
if (isCancelled) {
if (currentCount === count) isCancelled = false;
return data.value;
}
setState({
response: res
});
if (err) {
setState({
error: err
});
onError?.(err, args, res);
runPluginHooks('onError', err, args, res);
return Promise.reject(err);
}
const finalData = formatData ? formatData(result, args, res) : result;
setState({
data: finalData,
error: void 0
});
onSuccess?.(finalData, args, res);
runPluginHooks('onSuccess', finalData, args, res);
return finalData;
} catch (e) {
return Promise.reject(e);
} finally{
onFinally?.(args);
runPluginHooks('onFinally', args);
}
};
const run = async (...args)=>{
if (!ready.value) return;
return coreRequest(...args);
};
const refresh = ()=>run(...rawState.params);
const cancel = ()=>{
isCancelled = true;
setState({
loading: false
});
runPluginHooks('onCancel');
};
const mutate = (newData)=>{
const data = isFunction(newData) ? newData(rawState) : newData;
setState({
data
});
runPluginHooks('onMutate', data);
};
const optimisticUpdate = (newData, params = rawState.params)=>{
const oldData = rawState.data;
mutate(newData);
run(...params).catch(()=>{
if (void 0 !== oldData) mutate(oldData);
});
};
const debounceRun = hooks_debounce(run, debounceWait, {
maxWait: debounceMaxWait,
leading: debounceLeading,
trailing: debounceTrailing
});
const throttleRun = hooks_throttle(run, throttleWait, {
leading: throttleLeading,
trailing: throttleTrailing
});
return {
run,
refresh,
cancel,
mutate,
optimisticUpdate,
debounceRun,
throttleRun
};
}
function useCoreState(options) {
const state = {
data: options.initialData,
rawData: void 0,
response: void 0,
error: void 0,
params: options.defaultParams || [],
loading: false,
finished: false
};
const stateReactive = (0, external_vue_namespaceObject.shallowReactive)({
...state
});
const setState = (newState)=>{
Object.assign(state, newState);
Object.assign(stateReactive, newState);
};
return {
loading: (0, external_vue_namespaceObject.computed)(()=>stateReactive.loading),
finished: (0, external_vue_namespaceObject.computed)(()=>stateReactive.finished),
data: (0, external_vue_namespaceObject.computed)(()=>stateReactive.data),
rawData: (0, external_vue_namespaceObject.computed)(()=>stateReactive.response?.data),
error: (0, external_vue_namespaceObject.computed)(()=>stateReactive.error),
response: (0, external_vue_namespaceObject.computed)(()=>stateReactive.response),
params: (0, external_vue_namespaceObject.computed)(()=>stateReactive.params),
setState,
rawState: state
};
}
function usePlugins(plugins) {
const pluginHooks = (0, external_vue_namespaceObject.ref)([]);
const register = (context)=>{
pluginHooks.value = plugins.map((plugin)=>plugin(context)).filter(Boolean);
};
const runPluginHooks = (hook, ...args)=>{
const result = pluginHooks.value.map((pluginHook)=>pluginHook[hook]?.(...args)).filter(Boolean);
return Object.assign({}, ...result);
};
return {
register,
runPluginHooks
};
}
function mitt(n) {
return {
all: n = n || new Map,
on: function(t, e) {
var i = n.get(t);
i ? i.push(e) : n.set(t, [
e
]);
},
off: function(t, e) {
var i = n.get(t);
i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
},
emit: function(t, e) {
var i = n.get(t);
i && i.slice().map(function(n) {
n(e);
}), (i = n.get("*")) && i.slice().map(function(n) {
n(t, e);
});
}
};
}
const cacheEmitter = mitt();
const cache_emitter = cacheEmitter;
const CACHE_PROMISE = new Map();
const getCachePromise = (cacheKey)=>CACHE_PROMISE.get(cacheKey);
const deleteCachePromise = (cacheKey)=>{
CACHE_PROMISE.delete(cacheKey);
};
const setCachePromise = (cacheKey, promise)=>{
CACHE_PROMISE.set(cacheKey, promise);
promise.then((res)=>{
deleteCachePromise(cacheKey);
return res;
}).catch((err)=>{
deleteCachePromise(cacheKey);
throw err;
});
};
const useCachePlugin = define_plugin(({ options, setState, params })=>{
const { cacheKey, staleTime = 0, cacheTime = 600000, getCache: getCustomizeCache, setCache: setCustomizeCache } = options;
if (!cacheKey) return;
const isSelfEmit = (0, external_vue_namespaceObject.ref)(false);
const isUpdate = (0, external_vue_namespaceObject.ref)(true);
let currentServicePromise;
const isFresh = (time)=>staleTime === 1 / 0 || time + staleTime > Date.now();
const setCatchState = (catchData)=>{
setState({
...omit(catchData, [
'time',
'timer'
])
});
};
const _getCache = (key)=>getCustomizeCache ? getCustomizeCache(key, params.value) : getCache(key);
const _setCache = (key, cacheData)=>{
setCustomizeCache ? setCustomizeCache(key, cacheData) : setCache(key, cacheTime, cacheData);
};
const cache = _getCache(cacheKey);
if (cache) setCatchState(cache);
cache_emitter.on(cacheKey, (cache)=>{
if (isSelfEmit.value) {
isSelfEmit.value = false;
return;
}
setCatchState(cache);
});
return {
onBefore () {
const cache = _getCache(cacheKey);
if (!cache) return;
setCatchState(cache);
if (isFresh(cache.time)) return {
isReturned: true
};
},
onRequest (service, params) {
let servicePromise = getCachePromise(cacheKey);
if (servicePromise && servicePromise !== currentServicePromise) {
isSelfEmit.value = true;
isUpdate.value = false;
return {
servicePromise
};
}
servicePromise = service(...params);
currentServicePromise = servicePromise;
setCachePromise(cacheKey, servicePromise);
return {
servicePromise
};
},
onSuccess (data, params, response) {
_setCache(cacheKey, {
data,
params: params,
rawData: response?.data,
response,
time: Date.now()
});
const newCache = _getCache(cacheKey);
isSelfEmit.value = true;
if (isUpdate.value) cache_emitter.emit(cacheKey, newCache);
else {
isUpdate.value = true;
isSelfEmit.value = false;
}
}
};
});
const plugins_cache = useCachePlugin;
const useErrorRetryPlugin = define_plugin(({ finished, options, refresh })=>{
const { errorRetryCount, errorRetryInterval = 1000 } = options;
let timer;
const retryCountRef = (0, external_vue_namespaceObject.toRef)(errorRetryCount);
const retryIntervalRef = (0, external_vue_namespaceObject.toRef)(errorRetryInterval);
const errorCount = (0, external_vue_namespaceObject.ref)(0);
const isStopRetry = (0, external_vue_namespaceObject.computed)(()=>!retryCountRef.value || errorCount.value >= retryCountRef.value || !finished.value);
const clearTimer = ()=>{
timer && clearTimeout(timer);
};
const resetErrorCount = ()=>{
errorCount.value = 0;
};
const updateErrorCount = ()=>{
errorCount.value += 1;
};
(0, external_vue_namespaceObject.onUnmounted)(()=>{
clearTimer();
});
return {
onBefore () {
clearTimer();
},
onSuccess () {
resetErrorCount();
},
onError () {
if (isStopRetry.value) return resetErrorCount();
updateErrorCount();
timer = setTimeout(refresh, retryIntervalRef.value);
}
};
});
const error_retry = useErrorRetryPlugin;
const useLoadingPlugin = define_plugin(({ options, setState })=>{
const { loadingKeep = 0, loadingDelay = 0 } = options;
let startTime;
let delayTimer;
let keepTimer;
const loadingDelayRef = (0, external_vue_namespaceObject.toRef)(loadingDelay);
const loadingKeepRef = (0, external_vue_namespaceObject.toRef)(loadingKeep);
const clearDelayTimer = ()=>{
delayTimer && clearTimeout(delayTimer);
};
const clearKeepTimer = ()=>{
keepTimer && clearTimeout(keepTimer);
};
const startDelay = (ms, callback)=>{
clearDelayTimer();
delayTimer = setTimeout(callback, ms);
};
const startKeep = (ms, callback)=>{
clearKeepTimer();
keepTimer = setTimeout(callback, ms);
};
const setLoading = (loading)=>{
setState({
loading
});
};
return {
onBefore () {
startTime = Date.now();
loadingDelayRef.value ? startDelay(loadingDelayRef.value, ()=>setLoading(true)) : setLoading(true);
},
onFinallyFetchDone () {
clearDelayTimer();
const requestTime = Date.now() - startTime;
if (!loadingKeepRef.value || requestTime >= loadingKeepRef.value) setLoading(false);
else if (requestTime < loadingKeepRef.value) startKeep(loadingKeepRef.value - requestTime, ()=>{
setLoading(false);
});
}
};
});
const plugins_loading = useLoadingPlugin;
const usePollingPlugin = define_plugin(({ finished, refresh, options })=>{
const { pollingInterval = 0, pollingWhenDocumentHidden = false, pollingErrorRetryCount = 3 } = options;
let timer;
const errorCount = (0, external_vue_namespaceObject.ref)(0);
const pollingIntervalRef = (0, external_vue_namespaceObject.toRef)(pollingInterval);
const pollingErrorRetryCountRef = (0, external_vue_namespaceObject.toRef)(pollingErrorRetryCount);
const pollingWhenHiddenRef = (0, external_vue_namespaceObject.toRef)(pollingWhenDocumentHidden);
const documentVisibility = useDocumentVisibility();
const isStopPolling = (0, external_vue_namespaceObject.computed)(()=>pollingIntervalRef.value <= 0 || errorCount.value - 1 >= pollingErrorRetryCountRef.value && pollingErrorRetryCountRef.value !== 1 / 0 || !pollingWhenHiddenRef.value && 'hidden' === documentVisibility.value || !finished.value);
const clearTimer = ()=>{
timer && clearTimeout(timer);
};
const resetErrorCount = ()=>{
errorCount.value = 0;
};
const updateErrorCount = ()=>{
errorCount.value += 1;
};
(0, external_vue_namespaceObject.watch)(documentVisibility, ()=>{
if ('visible' === documentVisibility.value && !isStopPolling.value) refresh();
});
(0, external_vue_namespaceObject.onUnmounted)(()=>{
clearTimer();
});
return {
onBefore () {
clearTimer();
},
onSuccess () {
resetErrorCount();
},
onError () {
updateErrorCount();
},
onFinally () {
if (isStopPolling.value) return resetErrorCount();
timer = setTimeout(refresh, pollingIntervalRef.value);
}
};
});
const polling = usePollingPlugin;
const useRefreshOnWindowFocusPlugin = define_plugin(({ refresh, options, scope })=>{
const { refreshOnWindowFocus = false, focusTimespan = 5000 } = options;
const isRefreshOnWindowFocus = (0, external_vue_namespaceObject.toRef)(refreshOnWindowFocus);
const focusTimespanRef = (0, external_vue_namespaceObject.toRef)(focusTimespan);
const startTime = (0, external_vue_namespaceObject.ref)(Date.now());
const isFocus = useWindowFocus();
scope.run(()=>{
(0, external_vue_namespaceObject.watch)(isFocus, ()=>{
if (!isRefreshOnWindowFocus.value) return;
if (!isFocus.value) return startTime.value = Date.now();
if (focusTimespanRef.value && Date.now() - startTime.value < focusTimespanRef.value) return;
refresh();
});
});
});
const window_focus = useRefreshOnWindowFocusPlugin;
function useRequest(service, options = {}, plugins = []) {
const scope = (0, external_vue_namespaceObject.effectScope)();
const globalProvider = (0, external_vue_namespaceObject.inject)(GLOBAL_CONFIG_PROVIDER_SYMBOL, {});
const allPlugins = [
...plugins,
plugins_cache,
plugins_loading,
window_focus,
polling,
error_retry,
...globalProvider?.plugins || []
];
const config = Object.assign(options, globalProvider?.common);
const { register, runPluginHooks } = usePlugins(allPlugins);
const coreState = useCoreState(config);
const coreRequest = useCoreRequest(coreState, service, config, runPluginHooks);
const context = {
...coreState,
...coreRequest,
scope,
options: config
};
(0, external_vue_namespaceObject.onScopeDispose)(()=>{
scope.stop();
});
register(context);
if (!config.manual && true !== config.watchSource) coreRequest.run(...coreState.rawState.params);
scope.run(()=>{
true === config.watchSource && (0, external_vue_namespaceObject.watchEffect)(()=>{
coreRequest.run(...coreState.rawState.params);
});
!isBoolean(config.watchSource) && config.watchSource && (0, external_vue_namespaceObject.watch)(config.watchSource, ()=>{
coreRequest.run(...coreState.rawState.params);
}, {
deep: config.watchDeep
});
});
return {
...coreState,
...coreRequest
};
}
function usePagination(service, options = {}) {
const globalProvider = (0, external_vue_namespaceObject.inject)(GLOBAL_CONFIG_PROVIDER_SYMBOL, {});
const config = Object.assign(options, globalProvider?.pagination);
const { target, initialPage = 1, initialPageSize = 10, loadMoreOffset = 100, pageWatch = true, resetPageWhenPageSizeChange = true, addedMode, onSuccess } = config;
const page = (0, external_vue_namespaceObject.ref)(initialPage);
const pageSize = (0, external_vue_namespaceObject.ref)(initialPageSize);
const lastPage = (0, external_vue_namespaceObject.ref)(initialPage);
const addedModeRef = (0, external_vue_namespaceObject.ref)(addedMode);
const list = (0, external_vue_namespaceObject.ref)([]);
const fetchInstance = useRequest(()=>service({
page: page.value,
pageSize: pageSize.value
}), {
...omit(config, [
'target',
'initialPage',
'initialPageSize',
'pageWatch'
]),
onSuccess (data, params, response) {
onSuccess?.(data, params, response);
if (!addedModeRef.value) return;
list.value = (page.value <= lastPage.value ? data.list : [
...list.value,
...data.list
]) ?? [];
lastPage.value = page.value;
}
});
const total = (0, external_vue_namespaceObject.computed)(()=>fetchInstance.data.value?.total ?? 0);
const totalPage = (0, external_vue_namespaceObject.computed)(()=>Math.ceil(total.value / pageSize.value));
const isLastPage = (0, external_vue_namespaceObject.computed)(()=>page.value === totalPage.value);
const pageComputed = (0, external_vue_namespaceObject.computed)({
get () {
return page.value;
},
set (value) {
page.value = value;
pageWatch && fetchInstance.refresh();
}
});
const pageSizeComputed = (0, external_vue_namespaceObject.computed)({
get () {
return pageSize.value;
},
set (value) {
pageSize.value = value;
if (resetPageWhenPageSizeChange) pageComputed.value = 1;
}
});
useEventListener(target, 'scroll', (event)=>{
const { scrollHeight, scrollTop, clientHeight } = event.target;
if (scrollTop + clientHeight >= scrollHeight - loadMoreOffset && !isLastPage.value && fetchInstance.finished.value) pageComputed.value += 1;
});
return {
...fetchInstance,
list: (0, external_vue_namespaceObject.computed)(()=>addedModeRef.value ? list.value : fetchInstance.data.value?.list ?? []),
page: pageComputed,
pageSize: pageSizeComputed,
total,
totalPage,
isLastPage
};
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
value: true
});