mirror of
https://github.com/vbenjs/vue-vben-admin.git
synced 2025-08-27 13:21:51 +08:00
feat(demo): hooks useRequest 异步数据管理 (#3447)
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
export * from './onMountedOrActivated';
|
||||
export * from './useAttrs';
|
||||
export * from './useRefs';
|
||||
export * from './useRequest';
|
||||
export * from './useScrollTo';
|
||||
export * from './useWindowSizeFn';
|
||||
export { useTimeoutFn } from '@vueuse/core';
|
||||
|
147
packages/hooks/src/useRequest/Fetch.ts
Normal file
147
packages/hooks/src/useRequest/Fetch.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
import { reactive } from 'vue';
|
||||
|
||||
import type { FetchState, PluginReturn, Service, Subscribe, UseRequestOptions } from './types';
|
||||
import { isFunction } from './utils/isFunction';
|
||||
|
||||
export default class Fetch<TData, TParams extends any[]> {
|
||||
pluginImpls: PluginReturn<TData, TParams>[] = [];
|
||||
|
||||
count: number = 0;
|
||||
|
||||
state: FetchState<TData, TParams> = reactive({
|
||||
loading: false,
|
||||
params: undefined,
|
||||
data: undefined,
|
||||
error: undefined,
|
||||
});
|
||||
|
||||
constructor(
|
||||
public serviceRef: Service<TData, TParams>,
|
||||
public options: UseRequestOptions<TData, TParams>,
|
||||
public subscribe: Subscribe,
|
||||
public initState: Partial<FetchState<TData, TParams>> = {},
|
||||
) {
|
||||
this.setState({ loading: !options.manual, ...initState });
|
||||
}
|
||||
|
||||
setState(s: Partial<FetchState<TData, TParams>> = {}) {
|
||||
Object.assign(this.state, s);
|
||||
this.subscribe();
|
||||
}
|
||||
|
||||
runPluginHandler(event: keyof PluginReturn<TData, TParams>, ...rest: any[]) {
|
||||
// @ts-ignore
|
||||
const r = this.pluginImpls.map((i) => i[event]?.(...rest)).filter(Boolean);
|
||||
return Object.assign({}, ...r);
|
||||
}
|
||||
|
||||
async runAsync(...params: TParams): Promise<TData> {
|
||||
this.count += 1;
|
||||
const currentCount = this.count;
|
||||
|
||||
const {
|
||||
stopNow = false,
|
||||
returnNow = false,
|
||||
...state
|
||||
} = this.runPluginHandler('onBefore', params);
|
||||
|
||||
// stop request
|
||||
if (stopNow) {
|
||||
return new Promise(() => {});
|
||||
}
|
||||
|
||||
this.setState({
|
||||
loading: true,
|
||||
params,
|
||||
...state,
|
||||
});
|
||||
|
||||
// return now
|
||||
if (returnNow) {
|
||||
return Promise.resolve(state.data);
|
||||
}
|
||||
|
||||
this.options.onBefore?.(params);
|
||||
|
||||
try {
|
||||
// replace service
|
||||
let { servicePromise } = this.runPluginHandler('onRequest', this.serviceRef, params);
|
||||
|
||||
if (!servicePromise) {
|
||||
servicePromise = this.serviceRef(...params);
|
||||
}
|
||||
|
||||
const res = await servicePromise;
|
||||
|
||||
if (currentCount !== this.count) {
|
||||
// prevent run.then when request is canceled
|
||||
return new Promise(() => {});
|
||||
}
|
||||
|
||||
// const formattedResult = this.options.formatResultRef.current ? this.options.formatResultRef.current(res) : res;
|
||||
|
||||
this.setState({ data: res, error: undefined, loading: false });
|
||||
|
||||
this.options.onSuccess?.(res, params);
|
||||
this.runPluginHandler('onSuccess', res, params);
|
||||
|
||||
this.options.onFinally?.(params, res, undefined);
|
||||
|
||||
if (currentCount === this.count) {
|
||||
this.runPluginHandler('onFinally', params, res, undefined);
|
||||
}
|
||||
|
||||
return res;
|
||||
} catch (error) {
|
||||
if (currentCount !== this.count) {
|
||||
// prevent run.then when request is canceled
|
||||
return new Promise(() => {});
|
||||
}
|
||||
|
||||
this.setState({ error, loading: false });
|
||||
|
||||
this.options.onError?.(error, params);
|
||||
this.runPluginHandler('onError', error, params);
|
||||
|
||||
this.options.onFinally?.(params, undefined, error);
|
||||
|
||||
if (currentCount === this.count) {
|
||||
this.runPluginHandler('onFinally', params, undefined, error);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(...params: TParams) {
|
||||
this.runAsync(...params).catch((error) => {
|
||||
if (!this.options.onError) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel() {
|
||||
this.count += 1;
|
||||
this.setState({ loading: false });
|
||||
|
||||
this.runPluginHandler('onCancel');
|
||||
}
|
||||
|
||||
refresh() {
|
||||
// @ts-ignore
|
||||
this.run(...(this.state.params || []));
|
||||
}
|
||||
|
||||
refreshAsync() {
|
||||
// @ts-ignore
|
||||
return this.runAsync(...(this.state.params || []));
|
||||
}
|
||||
|
||||
mutate(data?: TData | ((oldData?: TData) => TData | undefined)) {
|
||||
const targetData = isFunction(data) ? data(this.state.data) : data;
|
||||
this.runPluginHandler('onMutate', targetData);
|
||||
this.setState({ data: targetData });
|
||||
}
|
||||
}
|
30
packages/hooks/src/useRequest/index.ts
Normal file
30
packages/hooks/src/useRequest/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import useAutoRunPlugin from './plugins/useAutoRunPlugin';
|
||||
import useCachePlugin from './plugins/useCachePlugin';
|
||||
import useDebouncePlugin from './plugins/useDebouncePlugin';
|
||||
import useLoadingDelayPlugin from './plugins/useLoadingDelayPlugin';
|
||||
import usePollingPlugin from './plugins/usePollingPlugin';
|
||||
import useRefreshOnWindowFocusPlugin from './plugins/useRefreshOnWindowFocusPlugin';
|
||||
import useRetryPlugin from './plugins/useRetryPlugin';
|
||||
import useThrottlePlugin from './plugins/useThrottlePlugin';
|
||||
import type { Service, UseRequestOptions, UseRequestPlugin } from './types';
|
||||
import { useRequestImplement } from './useRequestImplement';
|
||||
|
||||
export { clearCache } from './utils/cache';
|
||||
|
||||
export function useRequest<TData, TParams extends any[]>(
|
||||
service: Service<TData, TParams>,
|
||||
options?: UseRequestOptions<TData, TParams>,
|
||||
plugins?: UseRequestPlugin<TData, TParams>[],
|
||||
) {
|
||||
return useRequestImplement<TData, TParams>(service, options, [
|
||||
...(plugins || []),
|
||||
useDebouncePlugin,
|
||||
useLoadingDelayPlugin,
|
||||
usePollingPlugin,
|
||||
useRefreshOnWindowFocusPlugin,
|
||||
useThrottlePlugin,
|
||||
useAutoRunPlugin,
|
||||
useCachePlugin,
|
||||
useRetryPlugin,
|
||||
] as UseRequestPlugin<TData, TParams>[]);
|
||||
}
|
52
packages/hooks/src/useRequest/plugins/useAutoRunPlugin.ts
Normal file
52
packages/hooks/src/useRequest/plugins/useAutoRunPlugin.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { ref, unref, watch } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin } from '../types';
|
||||
|
||||
// support refreshDeps & ready
|
||||
const useAutoRunPlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ manual, ready = true, defaultParams = [], refreshDeps = [], refreshDepsAction },
|
||||
) => {
|
||||
const hasAutoRun = ref(false);
|
||||
|
||||
watch(
|
||||
() => unref(ready),
|
||||
(readyVal) => {
|
||||
if (!unref(manual) && readyVal) {
|
||||
hasAutoRun.value = true;
|
||||
fetchInstance.run(...defaultParams);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (refreshDeps.length) {
|
||||
watch(refreshDeps, () => {
|
||||
if (hasAutoRun.value) {
|
||||
return;
|
||||
}
|
||||
if (!manual) {
|
||||
if (refreshDepsAction) {
|
||||
refreshDepsAction();
|
||||
} else {
|
||||
fetchInstance.refresh();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
onBefore: () => {
|
||||
if (!unref(ready)) {
|
||||
return { stopNow: true };
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
useAutoRunPlugin.onInit = ({ ready = true, manual }) => {
|
||||
return {
|
||||
loading: !unref(manual) && unref(ready),
|
||||
};
|
||||
};
|
||||
|
||||
export default useAutoRunPlugin;
|
127
packages/hooks/src/useRequest/plugins/useCachePlugin.ts
Normal file
127
packages/hooks/src/useRequest/plugins/useCachePlugin.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { onUnmounted, ref, watchEffect } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin } from '../types';
|
||||
import type { CachedData } from '../utils/cache';
|
||||
import { getCache, setCache } from '../utils/cache';
|
||||
import { getCachePromise, setCachePromise } from '../utils/cachePromise';
|
||||
import { subscribe, trigger } from '../utils/cacheSubscribe';
|
||||
|
||||
const useCachePlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{
|
||||
cacheKey,
|
||||
cacheTime = 5 * 60 * 1000,
|
||||
staleTime = 0,
|
||||
setCache: customSetCache,
|
||||
getCache: customGetCache,
|
||||
},
|
||||
) => {
|
||||
const unSubscribeRef = ref<() => void>();
|
||||
const currentPromiseRef = ref<Promise<any>>();
|
||||
|
||||
const _setCache = (key: string, cachedData: CachedData) => {
|
||||
customSetCache ? customSetCache(cachedData) : setCache(key, cacheTime, cachedData);
|
||||
trigger(key, cachedData.data);
|
||||
};
|
||||
|
||||
const _getCache = (key: string, params: any[] = []) => {
|
||||
return customGetCache ? customGetCache(params) : getCache(key);
|
||||
};
|
||||
|
||||
watchEffect(() => {
|
||||
if (!cacheKey) return;
|
||||
|
||||
// get data from cache when init
|
||||
const cacheData = _getCache(cacheKey);
|
||||
if (cacheData && Object.hasOwnProperty.call(cacheData, 'data')) {
|
||||
fetchInstance.state.data = cacheData.data;
|
||||
fetchInstance.state.params = cacheData.params;
|
||||
|
||||
if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) {
|
||||
fetchInstance.state.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// subscribe same cachekey update, trigger update
|
||||
unSubscribeRef.value = subscribe(cacheKey, (data) => {
|
||||
fetchInstance.setState({ data });
|
||||
});
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
unSubscribeRef.value?.();
|
||||
});
|
||||
|
||||
if (!cacheKey) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
onBefore: (params) => {
|
||||
const cacheData = _getCache(cacheKey, params);
|
||||
|
||||
if (!cacheData || !Object.hasOwnProperty.call(cacheData, 'data')) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// If the data is fresh, stop request
|
||||
if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) {
|
||||
return {
|
||||
loading: false,
|
||||
data: cacheData?.data,
|
||||
error: undefined,
|
||||
returnNow: true,
|
||||
};
|
||||
} else {
|
||||
// If the data is stale, return data, and request continue
|
||||
return { data: cacheData?.data, error: undefined };
|
||||
}
|
||||
},
|
||||
onRequest: (service, args) => {
|
||||
let servicePromise = getCachePromise(cacheKey);
|
||||
|
||||
// If has servicePromise, and is not trigger by self, then use it
|
||||
if (servicePromise && servicePromise !== currentPromiseRef.value) {
|
||||
return { servicePromise };
|
||||
}
|
||||
|
||||
servicePromise = service(...args);
|
||||
currentPromiseRef.value = servicePromise;
|
||||
setCachePromise(cacheKey, servicePromise);
|
||||
|
||||
return { servicePromise };
|
||||
},
|
||||
onSuccess: (data, params) => {
|
||||
if (cacheKey) {
|
||||
// cancel subscribe, avoid trgger self
|
||||
unSubscribeRef.value?.();
|
||||
|
||||
_setCache(cacheKey, { data, params, time: new Date().getTime() });
|
||||
|
||||
// resubscribe
|
||||
unSubscribeRef.value = subscribe(cacheKey, (d) => {
|
||||
fetchInstance.setState({ data: d });
|
||||
});
|
||||
}
|
||||
},
|
||||
onMutate: (data) => {
|
||||
if (cacheKey) {
|
||||
// cancel subscribe, avoid trigger self
|
||||
unSubscribeRef.value?.();
|
||||
|
||||
_setCache(cacheKey, {
|
||||
data,
|
||||
params: fetchInstance.state.params,
|
||||
time: new Date().getTime(),
|
||||
});
|
||||
|
||||
// resubscribe
|
||||
unSubscribeRef.value = subscribe(cacheKey, (d) => {
|
||||
fetchInstance.setState({ data: d });
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default useCachePlugin;
|
71
packages/hooks/src/useRequest/plugins/useDebouncePlugin.ts
Normal file
71
packages/hooks/src/useRequest/plugins/useDebouncePlugin.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { DebouncedFunc, DebounceSettings } from 'lodash-es';
|
||||
import { debounce } from 'lodash-es';
|
||||
import { computed, ref, watchEffect } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin } from '../types';
|
||||
|
||||
const useDebouncePlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ debounceWait, debounceLeading, debounceTrailing, debounceMaxWait },
|
||||
) => {
|
||||
const debouncedRef = ref<DebouncedFunc<any>>();
|
||||
|
||||
const options = computed(() => {
|
||||
const ret: DebounceSettings = {};
|
||||
|
||||
if (debounceLeading !== undefined) {
|
||||
ret.leading = debounceLeading;
|
||||
}
|
||||
if (debounceTrailing !== undefined) {
|
||||
ret.trailing = debounceTrailing;
|
||||
}
|
||||
if (debounceMaxWait !== undefined) {
|
||||
ret.maxWait = debounceMaxWait;
|
||||
}
|
||||
|
||||
return ret;
|
||||
});
|
||||
|
||||
watchEffect(() => {
|
||||
if (debounceWait) {
|
||||
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
|
||||
|
||||
debouncedRef.value = debounce(
|
||||
(callback) => {
|
||||
callback();
|
||||
},
|
||||
debounceWait,
|
||||
options.value,
|
||||
);
|
||||
|
||||
// debounce runAsync should be promise
|
||||
// https://github.com/lodash/lodash/issues/4400#issuecomment-834800398
|
||||
fetchInstance.runAsync = (...args) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
debouncedRef.value?.(() => {
|
||||
_originRunAsync(...args)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return () => {
|
||||
debouncedRef.value?.cancel();
|
||||
fetchInstance.runAsync = _originRunAsync;
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
if (!debounceWait) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
onCancel: () => {
|
||||
debouncedRef.value?.cancel();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default useDebouncePlugin;
|
@@ -0,0 +1,45 @@
|
||||
import { ref, unref } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin, UseRequestTimeout } from '../types';
|
||||
|
||||
const useLoadingDelayPlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ loadingDelay, ready },
|
||||
) => {
|
||||
const timerRef = ref<UseRequestTimeout>();
|
||||
|
||||
if (!loadingDelay) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const cancelTimeout = () => {
|
||||
if (timerRef.value) {
|
||||
clearTimeout(timerRef.value);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
onBefore: () => {
|
||||
cancelTimeout();
|
||||
|
||||
// Two cases:
|
||||
// 1. ready === undefined
|
||||
// 2. ready === true
|
||||
if (unref(ready) !== false) {
|
||||
timerRef.value = setTimeout(() => {
|
||||
fetchInstance.setState({ loading: true });
|
||||
}, loadingDelay);
|
||||
}
|
||||
|
||||
return { loading: false };
|
||||
},
|
||||
onFinally: () => {
|
||||
cancelTimeout();
|
||||
},
|
||||
onCancel: () => {
|
||||
cancelTimeout();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default useLoadingDelayPlugin;
|
71
packages/hooks/src/useRequest/plugins/usePollingPlugin.ts
Normal file
71
packages/hooks/src/useRequest/plugins/usePollingPlugin.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { ref, watch } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin, UseRequestTimeout } from '../types';
|
||||
import { isDocumentVisible } from '../utils/isDocumentVisible';
|
||||
import subscribeReVisible from '../utils/subscribeReVisible';
|
||||
|
||||
const usePollingPlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 },
|
||||
) => {
|
||||
const timerRef = ref<UseRequestTimeout>();
|
||||
const unsubscribeRef = ref<() => void>();
|
||||
const countRef = ref<number>(0);
|
||||
|
||||
const stopPolling = () => {
|
||||
if (timerRef.value) {
|
||||
clearTimeout(timerRef.value);
|
||||
}
|
||||
unsubscribeRef.value?.();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => pollingInterval,
|
||||
() => {
|
||||
if (!pollingInterval) {
|
||||
stopPolling();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!pollingInterval) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
onBefore: () => {
|
||||
stopPolling();
|
||||
},
|
||||
onError: () => {
|
||||
countRef.value += 1;
|
||||
},
|
||||
onSuccess: () => {
|
||||
countRef.value = 0;
|
||||
},
|
||||
onFinally: () => {
|
||||
if (
|
||||
pollingErrorRetryCount === -1 ||
|
||||
// When an error occurs, the request is not repeated after pollingErrorRetryCount retries
|
||||
(pollingErrorRetryCount !== -1 && countRef.value <= pollingErrorRetryCount)
|
||||
) {
|
||||
timerRef.value = setTimeout(() => {
|
||||
// if pollingWhenHidden = false && document is hidden, then stop polling and subscribe revisible
|
||||
if (!pollingWhenHidden && !isDocumentVisible()) {
|
||||
unsubscribeRef.value = subscribeReVisible(() => {
|
||||
fetchInstance.refresh();
|
||||
});
|
||||
} else {
|
||||
fetchInstance.refresh();
|
||||
}
|
||||
}, pollingInterval);
|
||||
} else {
|
||||
countRef.value = 0;
|
||||
}
|
||||
},
|
||||
onCancel: () => {
|
||||
stopPolling();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default usePollingPlugin;
|
@@ -0,0 +1,37 @@
|
||||
import { onUnmounted, ref, watchEffect } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin } from '../types';
|
||||
import { limit } from '../utils/limit';
|
||||
import subscribeFocus from '../utils/subscribeFocus';
|
||||
|
||||
const useRefreshOnWindowFocusPlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ refreshOnWindowFocus, focusTimespan = 5000 },
|
||||
) => {
|
||||
const unsubscribeRef = ref<() => void>();
|
||||
|
||||
const stopSubscribe = () => {
|
||||
unsubscribeRef.value?.();
|
||||
};
|
||||
|
||||
watchEffect(() => {
|
||||
if (refreshOnWindowFocus) {
|
||||
const limitRefresh = limit(fetchInstance.refresh.bind(fetchInstance), focusTimespan);
|
||||
unsubscribeRef.value = subscribeFocus(() => {
|
||||
limitRefresh();
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
stopSubscribe();
|
||||
};
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
stopSubscribe();
|
||||
});
|
||||
|
||||
return {};
|
||||
};
|
||||
|
||||
export default useRefreshOnWindowFocusPlugin;
|
54
packages/hooks/src/useRequest/plugins/useRetryPlugin.ts
Normal file
54
packages/hooks/src/useRequest/plugins/useRetryPlugin.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin, UseRequestTimeout } from '../types';
|
||||
|
||||
const useRetryPlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ retryInterval, retryCount },
|
||||
) => {
|
||||
const timerRef = ref<UseRequestTimeout>();
|
||||
const countRef = ref(0);
|
||||
|
||||
const triggerByRetry = ref(false);
|
||||
|
||||
if (!retryCount) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
onBefore: () => {
|
||||
if (!triggerByRetry.value) {
|
||||
countRef.value = 0;
|
||||
}
|
||||
triggerByRetry.value = false;
|
||||
|
||||
if (timerRef.value) {
|
||||
clearTimeout(timerRef.value);
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
countRef.value = 0;
|
||||
},
|
||||
onError: () => {
|
||||
countRef.value += 1;
|
||||
if (retryCount === -1 || countRef.value <= retryCount) {
|
||||
// Exponential backoff
|
||||
const timeout = retryInterval ?? Math.min(1000 * 2 ** countRef.value, 30000);
|
||||
timerRef.value = setTimeout(() => {
|
||||
triggerByRetry.value = true;
|
||||
fetchInstance.refresh();
|
||||
}, timeout);
|
||||
} else {
|
||||
countRef.value = 0;
|
||||
}
|
||||
},
|
||||
onCancel: () => {
|
||||
countRef.value = 0;
|
||||
if (timerRef.value) {
|
||||
clearTimeout(timerRef.value);
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default useRetryPlugin;
|
63
packages/hooks/src/useRequest/plugins/useThrottlePlugin.ts
Normal file
63
packages/hooks/src/useRequest/plugins/useThrottlePlugin.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import type { DebouncedFunc, ThrottleSettings } from 'lodash-es';
|
||||
import { throttle } from 'lodash-es';
|
||||
import { ref, watchEffect } from 'vue';
|
||||
|
||||
import type { UseRequestPlugin } from '../types';
|
||||
|
||||
const useThrottlePlugin: UseRequestPlugin<any, any[]> = (
|
||||
fetchInstance,
|
||||
{ throttleWait, throttleLeading, throttleTrailing },
|
||||
) => {
|
||||
const throttledRef = ref<DebouncedFunc<any>>();
|
||||
|
||||
const options: ThrottleSettings = {};
|
||||
if (throttleLeading !== undefined) {
|
||||
options.leading = throttleLeading;
|
||||
}
|
||||
if (throttleTrailing !== undefined) {
|
||||
options.trailing = throttleTrailing;
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
if (throttleWait) {
|
||||
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
|
||||
|
||||
throttledRef.value = throttle(
|
||||
(callback) => {
|
||||
callback();
|
||||
},
|
||||
throttleWait,
|
||||
options,
|
||||
);
|
||||
|
||||
// throttle runAsync should be promise
|
||||
// https://github.com/lodash/lodash/issues/4400#issuecomment-834800398
|
||||
fetchInstance.runAsync = (...args) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
throttledRef.value?.(() => {
|
||||
_originRunAsync(...args)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return () => {
|
||||
fetchInstance.runAsync = _originRunAsync;
|
||||
throttledRef.value?.cancel();
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
if (!throttleWait) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
onCancel: () => {
|
||||
throttledRef.value?.cancel();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default useThrottlePlugin;
|
124
packages/hooks/src/useRequest/types.ts
Normal file
124
packages/hooks/src/useRequest/types.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import type { MaybeRef, Ref, WatchSource } from 'vue';
|
||||
|
||||
import type Fetch from './Fetch';
|
||||
import type { CachedData } from './utils/cache';
|
||||
|
||||
export type Service<TData, TParams extends any[]> = (...args: TParams) => Promise<TData>;
|
||||
export type Subscribe = () => void;
|
||||
|
||||
// for Fetch
|
||||
export interface FetchState<TData, TParams extends any[]> {
|
||||
loading: boolean;
|
||||
params?: TParams;
|
||||
data?: TData;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
export interface PluginReturn<TData, TParams extends any[]> {
|
||||
onBefore?: (params: TParams) =>
|
||||
| ({
|
||||
stopNow?: boolean;
|
||||
returnNow?: boolean;
|
||||
} & Partial<FetchState<TData, TParams>>)
|
||||
| void;
|
||||
|
||||
onRequest?: (
|
||||
service: Service<TData, TParams>,
|
||||
params: TParams,
|
||||
) => {
|
||||
servicePromise?: Promise<TData>;
|
||||
};
|
||||
|
||||
onSuccess?: (data: TData, params: TParams) => void;
|
||||
onError?: (e: Error, params: TParams) => void;
|
||||
onFinally?: (params: TParams, data?: TData, e?: Error) => void;
|
||||
onCancel?: () => void;
|
||||
onMutate?: (data: TData) => void;
|
||||
}
|
||||
|
||||
// for useRequestImplement
|
||||
export interface UseRequestOptions<TData, TParams extends any[]> {
|
||||
manual?: MaybeRef<boolean>;
|
||||
|
||||
onBefore?: (params: TParams) => void;
|
||||
onSuccess?: (data: TData, params: TParams) => void;
|
||||
onError?: (e: Error, params: TParams) => void;
|
||||
// formatResult?: (res: any) => TData;
|
||||
onFinally?: (params: TParams, data?: TData, e?: Error) => void;
|
||||
|
||||
defaultParams?: TParams;
|
||||
|
||||
// refreshDeps
|
||||
refreshDeps?: WatchSource<any>[];
|
||||
refreshDepsAction?: () => void;
|
||||
|
||||
// loading delay
|
||||
loadingDelay?: number;
|
||||
|
||||
// polling
|
||||
pollingInterval?: number;
|
||||
pollingWhenHidden?: boolean;
|
||||
pollingErrorRetryCount?: number;
|
||||
|
||||
// refresh on window focus
|
||||
refreshOnWindowFocus?: boolean;
|
||||
focusTimespan?: number;
|
||||
|
||||
// debounce
|
||||
debounceWait?: number;
|
||||
debounceLeading?: boolean;
|
||||
debounceTrailing?: boolean;
|
||||
debounceMaxWait?: number;
|
||||
|
||||
// throttle
|
||||
throttleWait?: number;
|
||||
throttleLeading?: boolean;
|
||||
throttleTrailing?: boolean;
|
||||
|
||||
// cache
|
||||
cacheKey?: string;
|
||||
cacheTime?: number;
|
||||
staleTime?: number;
|
||||
setCache?: (data: CachedData<TData, TParams>) => void;
|
||||
getCache?: (params: TParams) => CachedData<TData, TParams> | undefined;
|
||||
|
||||
// retry
|
||||
retryCount?: number;
|
||||
retryInterval?: number;
|
||||
|
||||
// ready
|
||||
ready?: MaybeRef<boolean>;
|
||||
|
||||
// [key: string]: any;
|
||||
}
|
||||
|
||||
export interface UseRequestPlugin<TData, TParams extends any[]> {
|
||||
// eslint-disable-next-line prettier/prettier
|
||||
(fetchInstance: Fetch<TData, TParams>, options: UseRequestOptions<TData, TParams>): PluginReturn<
|
||||
TData,
|
||||
TParams
|
||||
>;
|
||||
onInit?: (options: UseRequestOptions<TData, TParams>) => Partial<FetchState<TData, TParams>>;
|
||||
}
|
||||
|
||||
// for index
|
||||
// export type OptionsWithoutFormat<TData, TParams extends any[]> = Omit<Options<TData, TParams>, 'formatResult'>;
|
||||
|
||||
// export interface OptionsWithFormat<TData, TParams extends any[], TFormated, TTFormated extends TFormated = any> extends Omit<Options<TTFormated, TParams>, 'formatResult'> {
|
||||
// formatResult: (res: TData) => TFormated;
|
||||
// };
|
||||
|
||||
export interface UseRequestResult<TData, TParams extends any[]> {
|
||||
loading: Ref<boolean>;
|
||||
data: Ref<TData>;
|
||||
error: Ref<Error>;
|
||||
params: Ref<TParams | []>;
|
||||
cancel: Fetch<TData, TParams>['cancel'];
|
||||
refresh: Fetch<TData, TParams>['refresh'];
|
||||
refreshAsync: Fetch<TData, TParams>['refreshAsync'];
|
||||
run: Fetch<TData, TParams>['run'];
|
||||
runAsync: Fetch<TData, TParams>['runAsync'];
|
||||
mutate: Fetch<TData, TParams>['mutate'];
|
||||
}
|
||||
|
||||
export type UseRequestTimeout = ReturnType<typeof setTimeout>;
|
49
packages/hooks/src/useRequest/useRequestImplement.ts
Normal file
49
packages/hooks/src/useRequest/useRequestImplement.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
import { onMounted, onUnmounted, toRefs } from 'vue';
|
||||
|
||||
import Fetch from './Fetch';
|
||||
import type { Service, UseRequestOptions, UseRequestPlugin, UseRequestResult } from './types';
|
||||
|
||||
export function useRequestImplement<TData, TParams extends any[]>(
|
||||
service: Service<TData, TParams>,
|
||||
options: UseRequestOptions<TData, TParams> = {},
|
||||
plugins: UseRequestPlugin<TData, TParams>[] = [],
|
||||
) {
|
||||
const { manual = false, ...rest } = options;
|
||||
const fetchOptions = { manual, ...rest };
|
||||
|
||||
const initState = plugins.map((p) => p?.onInit?.(fetchOptions)).filter(Boolean);
|
||||
|
||||
const fetchInstance = new Fetch<TData, TParams>(
|
||||
service,
|
||||
fetchOptions,
|
||||
() => {},
|
||||
Object.assign({}, ...initState),
|
||||
);
|
||||
|
||||
fetchInstance.options = fetchOptions;
|
||||
// run all plugins hooks
|
||||
fetchInstance.pluginImpls = plugins.map((p) => p(fetchInstance, fetchOptions));
|
||||
|
||||
onMounted(() => {
|
||||
if (!manual) {
|
||||
const params = fetchInstance.state.params || options.defaultParams || [];
|
||||
// @ts-ignore
|
||||
fetchInstance.run(...params);
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
fetchInstance.cancel();
|
||||
});
|
||||
|
||||
return {
|
||||
...toRefs(fetchInstance.state),
|
||||
cancel: fetchInstance.cancel.bind(fetchInstance),
|
||||
mutate: fetchInstance.mutate.bind(fetchInstance),
|
||||
refresh: fetchInstance.refresh.bind(fetchInstance),
|
||||
refreshAsync: fetchInstance.refreshAsync.bind(fetchInstance),
|
||||
run: fetchInstance.run.bind(fetchInstance),
|
||||
runAsync: fetchInstance.runAsync.bind(fetchInstance),
|
||||
} as UseRequestResult<TData, TParams>;
|
||||
}
|
48
packages/hooks/src/useRequest/utils/cache.ts
Normal file
48
packages/hooks/src/useRequest/utils/cache.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
type Timer = ReturnType<typeof setTimeout>;
|
||||
type CachedKey = string | number;
|
||||
|
||||
export interface CachedData<TData = any, TParams = any> {
|
||||
data: TData;
|
||||
params: TParams;
|
||||
time: number;
|
||||
}
|
||||
|
||||
interface RecordData extends CachedData {
|
||||
timer: Timer | undefined;
|
||||
}
|
||||
|
||||
const cache = new Map<CachedKey, RecordData>();
|
||||
|
||||
export const setCache = (key: CachedKey, cacheTime: number, cachedData: CachedData) => {
|
||||
const currentCache = cache.get(key);
|
||||
if (currentCache?.timer) {
|
||||
clearTimeout(currentCache.timer);
|
||||
}
|
||||
|
||||
let timer: Timer | undefined = undefined;
|
||||
|
||||
if (cacheTime > -1) {
|
||||
// if cache out, clear it
|
||||
timer = setTimeout(() => {
|
||||
cache.delete(key);
|
||||
}, cacheTime);
|
||||
}
|
||||
|
||||
cache.set(key, {
|
||||
...cachedData,
|
||||
timer,
|
||||
});
|
||||
};
|
||||
|
||||
export const getCache = (key: CachedKey) => {
|
||||
return cache.get(key);
|
||||
};
|
||||
|
||||
export const clearCache = (key?: string | string[]) => {
|
||||
if (key) {
|
||||
const cacheKeys = Array.isArray(key) ? key : [key];
|
||||
cacheKeys.forEach((cacheKey) => cache.delete(cacheKey));
|
||||
} else {
|
||||
cache.clear();
|
||||
}
|
||||
};
|
23
packages/hooks/src/useRequest/utils/cachePromise.ts
Normal file
23
packages/hooks/src/useRequest/utils/cachePromise.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
type CachedKey = string | number;
|
||||
|
||||
const cachePromise = new Map<CachedKey, Promise<any>>();
|
||||
|
||||
export const getCachePromise = (cacheKey: CachedKey) => {
|
||||
return cachePromise.get(cacheKey);
|
||||
};
|
||||
|
||||
export const setCachePromise = (cacheKey: CachedKey, promise: Promise<any>) => {
|
||||
// Should cache the same promise, cannot be promise.finally
|
||||
// Because the promise.finally will change the reference of the promise
|
||||
cachePromise.set(cacheKey, promise);
|
||||
|
||||
// no use promise.finally for compatibility
|
||||
promise
|
||||
.then((res) => {
|
||||
cachePromise.delete(cacheKey);
|
||||
return res;
|
||||
})
|
||||
.catch(() => {
|
||||
cachePromise.delete(cacheKey);
|
||||
});
|
||||
};
|
22
packages/hooks/src/useRequest/utils/cacheSubscribe.ts
Normal file
22
packages/hooks/src/useRequest/utils/cacheSubscribe.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
type Listener = (data: any) => void;
|
||||
|
||||
const listeners: Record<string, Listener[]> = {};
|
||||
|
||||
export const trigger = (key: string, data: any) => {
|
||||
if (listeners[key]) {
|
||||
listeners[key].forEach((item) => item(data));
|
||||
}
|
||||
};
|
||||
|
||||
export const subscribe = (key: string, listener: Listener) => {
|
||||
if (!listeners[key]) {
|
||||
listeners[key] = [];
|
||||
}
|
||||
|
||||
listeners[key].push(listener);
|
||||
|
||||
return function unsubscribe() {
|
||||
const index = listeners[key].indexOf(listener);
|
||||
listeners[key].splice(index, 1);
|
||||
};
|
||||
};
|
5
packages/hooks/src/useRequest/utils/isBrowser.ts
Normal file
5
packages/hooks/src/useRequest/utils/isBrowser.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export const isBrowser = !!(
|
||||
typeof window !== 'undefined' &&
|
||||
window.document &&
|
||||
window.document.createElement
|
||||
);
|
8
packages/hooks/src/useRequest/utils/isDocumentVisible.ts
Normal file
8
packages/hooks/src/useRequest/utils/isDocumentVisible.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { isBrowser } from './isBrowser';
|
||||
|
||||
export function isDocumentVisible(): boolean {
|
||||
if (isBrowser) {
|
||||
return document.visibilityState !== 'hidden';
|
||||
}
|
||||
return true;
|
||||
}
|
2
packages/hooks/src/useRequest/utils/isFunction.ts
Normal file
2
packages/hooks/src/useRequest/utils/isFunction.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export const isFunction = (value: unknown): value is (...args: any) => any =>
|
||||
typeof value === 'function';
|
8
packages/hooks/src/useRequest/utils/isOnline.ts
Normal file
8
packages/hooks/src/useRequest/utils/isOnline.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { isBrowser } from './isBrowser';
|
||||
|
||||
export function isOnline(): boolean {
|
||||
if (isBrowser && typeof navigator.onLine !== 'undefined') {
|
||||
return navigator.onLine;
|
||||
}
|
||||
return true;
|
||||
}
|
12
packages/hooks/src/useRequest/utils/limit.ts
Normal file
12
packages/hooks/src/useRequest/utils/limit.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export function limit(fn: any, timespan: number) {
|
||||
let pending = false;
|
||||
|
||||
return (...args: any[]) => {
|
||||
if (pending) return;
|
||||
pending = true;
|
||||
fn(...args);
|
||||
setTimeout(() => {
|
||||
pending = false;
|
||||
}, timespan);
|
||||
};
|
||||
}
|
30
packages/hooks/src/useRequest/utils/subscribeFocus.ts
Normal file
30
packages/hooks/src/useRequest/utils/subscribeFocus.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { isBrowser } from './isBrowser';
|
||||
import { isDocumentVisible } from './isDocumentVisible';
|
||||
import { isOnline } from './isOnline';
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
const listeners: Listener[] = [];
|
||||
|
||||
if (isBrowser) {
|
||||
const revalidate = () => {
|
||||
if (!isDocumentVisible() || !isOnline()) return;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
const listener = listeners[i];
|
||||
listener();
|
||||
}
|
||||
};
|
||||
window.addEventListener('visibilitychange', revalidate, false);
|
||||
window.addEventListener('focus', revalidate, false);
|
||||
}
|
||||
|
||||
export default function subscribe(listener: Listener) {
|
||||
listeners.push(listener);
|
||||
|
||||
return function unsubscribe() {
|
||||
const index = listeners.indexOf(listener);
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
};
|
||||
}
|
25
packages/hooks/src/useRequest/utils/subscribeReVisible.ts
Normal file
25
packages/hooks/src/useRequest/utils/subscribeReVisible.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { isBrowser } from './isBrowser';
|
||||
import { isDocumentVisible } from './isDocumentVisible';
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
const listeners: Listener[] = [];
|
||||
|
||||
if (isBrowser) {
|
||||
const revalidate = () => {
|
||||
if (!isDocumentVisible()) return;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
const listener = listeners[i];
|
||||
listener();
|
||||
}
|
||||
};
|
||||
window.addEventListener('visibilitychange', revalidate, false);
|
||||
}
|
||||
|
||||
export default function subscribe(listener: Listener) {
|
||||
listeners.push(listener);
|
||||
return function unsubscribe() {
|
||||
const index = listeners.indexOf(listener);
|
||||
listeners.splice(index, 1);
|
||||
};
|
||||
}
|
Reference in New Issue
Block a user