UNPKG

@caikengren/uni-use-request

Version:
987 lines (961 loc) 35 kB
(function(exports, __vue_devtools_api, vue, __caikengren_uni_hooks_shared, __dcloudio_uni_app) { Object.defineProperty(exports, '__esModule', { value: true }); //#region rolldown:runtime var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion __vue_devtools_api = __toESM(__vue_devtools_api); vue = __toESM(vue); __caikengren_uni_hooks_shared = __toESM(__caikengren_uni_hooks_shared); __dcloudio_uni_app = __toESM(__dcloudio_uni_app); //#region src/devtools/store.ts var RegisterDevToolsStore = class { constructor() { this.requestInstances = /* @__PURE__ */ new Map(); this.listeners = []; } emit(payload) { this.listeners.forEach((item) => item(payload)); } subscribe(listener) { this.listeners.push(listener); return () => { const index = this.listeners.indexOf(listener); this.listeners.splice(index, 1); }; } insert(key, payload) { this.requestInstances.set(key, { ...payload }); this.emit({ key, ...payload }); } update(key, payload) { if (this.has(key)) this.requestInstances.set(key, { ...this.requestInstances.get(key), ...payload }); } has(key) { return this.requestInstances.has(key); } reset(key) { if (this.requestInstances.has(key)) { const current = this.requestInstances.get(key); this.requestInstances.clear(); this.insert(key, current); } else this.requestInstances.clear(); } getAll() { return this.requestInstances; } }; const devToolsStore = new RegisterDevToolsStore(); var store_default = devToolsStore; //#endregion //#region src/devtools/utils.ts var HashTable = class { constructor() { this.table = {}; this.hashTable = {}; } insert(str) { const symbolCode = Symbol(str); this.table[str] = true; this.hashTable[symbolCode] = str; return symbolCode; } find(symbolCode) { return this.hashTable[symbolCode]; } }; const HashTableInstance = new HashTable(); function getFunctionName(func) { const match = func.toString().match(/^function\s+([^\s(]+)/); return match ? match[1] : ""; } function getArrowFunctionName(func) { const match = func.toString().match(/([a-z$_][\w$]*)\s*\(/i); return match ? match[1].trim() : ""; } function getRequestTagBg(type) { if (type === "pending") return 16747520; if (type === "done") return 6586111; if (type === "error") return 16724736; if (type === "cancel") return 10500409; if (type === "mutate") return 27647; return 4873398; } //#endregion //#region src/devtools/devtools.ts const pluginId = "vue-hooks-plus"; const pluginName = "Vue Hooks Plus 🍭"; const pluginLogo = "https://raw.githubusercontent.com/InhiblabCore/vue-hooks-plus/c3b984112610ef3fb21140a0beb27b4a228fe0b3/packages/hooks/docs/public/logo.svg"; let currentStateId; const controlMap = /* @__PURE__ */ new Map(); function setupDevtools(app) { (0, __vue_devtools_api.setupDevtoolsPlugin)({ id: pluginId, label: pluginName, packageName: "vue-hooks-plus", homepage: "https://inhiblabcore.github.io/docs/hooks", logo: pluginLogo, app, settings: { baseSort: { type: "choice", component: "button-group", label: "Sort Cache Entries", options: [{ label: "ASC", value: 1 }, { label: "DESC", value: -1 }], defaultValue: 1 } } }, (api) => { api.addTimelineLayer({ id: pluginId, label: pluginName, color: 16767308 }); api.addInspector({ id: pluginId, label: pluginName, icon: "api", treeFilterPlaceholder: "Search useRequest", actions: [{ icon: "delete", tooltip: "Clear useRequest root ", action: () => { store_default.reset(currentStateId); api.sendInspectorTree(pluginId); api.sendInspectorState(pluginId); } }] }); store_default.subscribe((event) => { store_default.update(event.key, { time: event.time, type: event.type }); api.sendInspectorTree(pluginId); api.sendInspectorState(pluginId); api.addTimelineEvent({ layerId: pluginId, event: { title: event.type, subtitle: `data: ${JSON.stringify(event.data)}`, time: api.now(), data: { ...event } } }); }); api.on.getInspectorTree((payload) => { if (payload.inspectorId === pluginId) { controlMap.clear(); const settings = api.getSettings(); const queries = store_default.getAll(); let sortedArray = []; if (settings.baseSort === 1) sortedArray = Array.from(queries.entries()).sort((a, b) => { var _b$1$time, _b$, _a$1$time, _a$; return ((_b$1$time = (_b$ = b[1]) === null || _b$ === void 0 ? void 0 : _b$.time) !== null && _b$1$time !== void 0 ? _b$1$time : 0) - ((_a$1$time = (_a$ = a[1]) === null || _a$ === void 0 ? void 0 : _a$.time) !== null && _a$1$time !== void 0 ? _a$1$time : 0); }); else sortedArray = Array.from(queries.entries()).sort((a, b) => { var _a$1$time2, _a$2, _b$1$time2, _b$2; return ((_a$1$time2 = (_a$2 = a[1]) === null || _a$2 === void 0 ? void 0 : _a$2.time) !== null && _a$1$time2 !== void 0 ? _a$1$time2 : 0) - ((_b$1$time2 = (_b$2 = b[1]) === null || _b$2 === void 0 ? void 0 : _b$2.time) !== null && _b$1$time2 !== void 0 ? _b$1$time2 : 0); }); const filtered = sortedArray.filter((item) => new RegExp(payload.filter, "g").test(item[0])).map((item) => { var _item$, _item$2, _item$3; return { id: item[0], label: item[0], tags: ((_item$ = item[1]) === null || _item$ === void 0 ? void 0 : _item$.type) ? [{ label: `${(_item$2 = item[1]) === null || _item$2 === void 0 ? void 0 : _item$2.type}`, textColor: 16777215, backgroundColor: getRequestTagBg((_item$3 = item[1]) === null || _item$3 === void 0 ? void 0 : _item$3.type) }] : [] }; }); payload.rootNodes = [{ id: "vue-hooks-plus-useRequest", label: "useRequest", tags: [{ label: "Root", textColor: 16777215, backgroundColor: 4372611 }], children: filtered !== null && filtered !== void 0 ? filtered : [] }]; } }); api.on.getInspectorState((payload) => { currentStateId = payload.nodeId; let pluginsIndex = 0; if (payload.inspectorId === pluginId) { const queries = store_default.getAll(); if (payload.nodeId) { var _currentSource$instan, _currentSource$instan2; const currentSource = queries.get(payload.nodeId); if (!currentSource) return; payload.state = { "Details": [{ key: "Key", value: payload.nodeId }, { key: "Request Name", value: currentSource.requestName }], "Data Explorer": Object.keys(currentSource.instance.state).map((item) => ({ key: item, value: (0, vue.unref)(currentSource.instance.state[item]) })), "Option": Object.keys(currentSource.instance.options).map((item) => ({ key: item, value: currentSource.instance.options[item] })), "Plugins 🧩": (_currentSource$instan = (_currentSource$instan2 = currentSource.instance.pluginImpls) === null || _currentSource$instan2 === void 0 || (_currentSource$instan2 = _currentSource$instan2.map((_, index) => { var _currentSource$instan3, _currentSource$instan4, _currentSource$instan5; const pluginName$1 = currentSource === null || currentSource === void 0 || (_currentSource$instan3 = currentSource.instance) === null || _currentSource$instan3 === void 0 || (_currentSource$instan3 = _currentSource$instan3.pluginImpls) === null || _currentSource$instan3 === void 0 || (_currentSource$instan3 = _currentSource$instan3[index]) === null || _currentSource$instan3 === void 0 ? void 0 : _currentSource$instan3.name; if (!pluginName$1) { if (index !== pluginsIndex) pluginsIndex++; } return { key: pluginName$1 ? pluginName$1 : `plugin ${pluginsIndex}`, value: (_currentSource$instan4 = currentSource === null || currentSource === void 0 || (_currentSource$instan5 = currentSource.instance) === null || _currentSource$instan5 === void 0 || (_currentSource$instan5 = _currentSource$instan5.pluginImpls) === null || _currentSource$instan5 === void 0 ? void 0 : _currentSource$instan5[index]) !== null && _currentSource$instan4 !== void 0 ? _currentSource$instan4 : null }; })) === null || _currentSource$instan2 === void 0 ? void 0 : _currentSource$instan2.filter((item) => Object.keys(item.value).length !== 0)) !== null && _currentSource$instan !== void 0 ? _currentSource$instan : [] }; } } }); }); } //#endregion //#region src/devtools/index.ts var devtools_default = { install(app) { setupDevtools(app); } }; //#endregion //#region src/plugins/useAutoRunPlugin.ts const useAutoRunPlugin = (fetchInstance, { manual, ready = true, refreshDeps = [], refreshDepsAction }) => { const hasAutoRun = (0, vue.ref)(false); (0, vue.watchEffect)(() => { if (!manual && fetchInstance.options.refreshDeps !== true) hasAutoRun.value = (0, vue.unref)(ready); }); if (Array.isArray(refreshDeps)) (0, vue.watch)([hasAutoRun, ...refreshDeps], ([autoRun]) => { if (!autoRun) return; if (!manual && autoRun) if (refreshDepsAction) refreshDepsAction(); else fetchInstance.refresh(); }, { deep: true, immediate: false }); else (0, vue.watch)(hasAutoRun, (h) => { if (!manual && h) if (refreshDepsAction) refreshDepsAction(); else fetchInstance.refresh(); }); return { name: "autoRunPlugin", onBefore: () => { if (!(0, vue.unref)(ready)) return { stopNow: true }; } }; }; useAutoRunPlugin.onInit = ({ ready = true, manual }) => ({ loading: !manual && (0, vue.unref)(ready) }); var useAutoRunPlugin_default = useAutoRunPlugin; //#endregion //#region src/utils/cache.ts const cache = /* @__PURE__ */ new Map(); function setCache(key, cacheTime, cachedData) { const currentCache = cache.get(key); if (currentCache === null || currentCache === void 0 ? void 0 : currentCache.timer) clearTimeout(currentCache.timer); let timer; if (cacheTime > -1) timer = setTimeout(() => { cache.delete(key); }, cacheTime); cache.set(key, { ...cachedData, timer }); } const getCache = (key) => cache.get(key); function clearCache(key) { if (key) (Array.isArray(key) ? key : [key]).forEach((cacheKey) => cache.delete(cacheKey)); else cache.clear(); } //#endregion //#region src/utils/cachePromise.ts const cachePromise = /* @__PURE__ */ new Map(); const getCachePromise = (cacheKey) => cachePromise.get(cacheKey); function setCachePromise(cacheKey, promise) { cachePromise.set(cacheKey, promise); promise.then((res) => { cachePromise.delete(cacheKey); return res; }).catch((err) => { cachePromise.delete(cacheKey); throw err; }); } //#endregion //#region src/utils/cacheSubscribe.ts const listeners = {}; const otherListeners = []; function trigger(key, data) { if (listeners[key]) { listeners[key].forEach((item) => item(data)); otherListeners.forEach((item) => item({ type: key, data })); } } function subscribe(key, listener) { if (!listeners[key]) listeners[key] = []; listeners[key].push(listener); return function unsubscribe() { const index = listeners[key].indexOf(listener); listeners[key].splice(index, 1); }; } //#endregion //#region src/plugins/useCachePlugin.ts const useCachePlugin = (fetchInstance, { cacheKey, cacheTime = 300 * 1e3, staleTime = 0, setCache: customSetCache, getCache: customGetCache }) => { const unSubscribeRef = (0, vue.ref)(); const currentPromiseRef = (0, vue.ref)(); const _setCache = (key, cachedData) => { if (customSetCache) customSetCache(cachedData); else setCache(key, cacheTime, cachedData); trigger(key, cachedData.data); }; const _getCache = (key, params = []) => { if (customGetCache) return customGetCache(params); return getCache(key); }; (0, vue.watchEffect)(() => { if (!cacheKey) return; const cacheData = _getCache(cacheKey); if (cacheData && Object.hasOwnProperty.call(cacheData, "data")) { fetchInstance.state.data = cacheData.data; fetchInstance.state.params = cacheData.params; if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData.time <= staleTime) fetchInstance.state.loading = false; } unSubscribeRef.value = subscribe(cacheKey, (data) => { fetchInstance.setState({ data }); }); }); (0, vue.onScopeDispose)(() => { var _unSubscribeRef$value; (_unSubscribeRef$value = unSubscribeRef.value) === null || _unSubscribeRef$value === void 0 || _unSubscribeRef$value.call(unSubscribeRef); }); if (!cacheKey) return {}; return { name: "cachePlugin", onBefore: (params) => { const cacheData = _getCache(cacheKey, params); if (!cacheData || !Object.hasOwnProperty.call(cacheData, "data")) return {}; if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData.time <= staleTime) return { loading: false, data: cacheData === null || cacheData === void 0 ? void 0 : cacheData.data, returnNow: true }; return { data: cacheData === null || cacheData === void 0 ? void 0 : cacheData.data }; }, onRequest: (service, args) => { let servicePromise = getCachePromise(cacheKey); if (servicePromise && servicePromise !== currentPromiseRef.value) return { servicePromise }; servicePromise = service(...args); currentPromiseRef.value = servicePromise; setCachePromise(cacheKey, servicePromise); return { servicePromise }; }, onSuccess: (data, params) => { if (cacheKey) { var _unSubscribeRef$value2; (_unSubscribeRef$value2 = unSubscribeRef.value) === null || _unSubscribeRef$value2 === void 0 || _unSubscribeRef$value2.call(unSubscribeRef); _setCache(cacheKey, { data, params, time: (/* @__PURE__ */ new Date()).getTime() }); unSubscribeRef.value = subscribe(cacheKey, (d) => { fetchInstance.setState({ data: d }); }); } }, onMutate: (data) => { if (cacheKey) { var _unSubscribeRef$value3; (_unSubscribeRef$value3 = unSubscribeRef.value) === null || _unSubscribeRef$value3 === void 0 || _unSubscribeRef$value3.call(unSubscribeRef); _setCache(cacheKey, { data, params: fetchInstance.state.params, time: (/* @__PURE__ */ new Date()).getTime() }); unSubscribeRef.value = subscribe(cacheKey, (d) => { fetchInstance.setState({ data: d }); }); } } }; }; var useCachePlugin_default = useCachePlugin; //#endregion //#region src/plugins/useDebouncePlugin.ts const useDebouncePlugin = (fetchInstance, { debounceWait, debounceMaxWait }) => { const debouncedRef = (0, vue.ref)(); (0, vue.watchEffect)((onInvalidate) => { if ((0, vue.unref)(debounceWait)) { const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance); debouncedRef.value = (0, __caikengren_uni_hooks_shared.createFilterWrapper)((0, __caikengren_uni_hooks_shared.debounceFilter)(debounceWait || 200, { maxWait: (0, vue.unref)(debounceMaxWait) }), (callback) => { callback(); }); fetchInstance.runAsync = (...args) => new Promise((resolve, reject) => { var _debouncedRef$value; (_debouncedRef$value = debouncedRef.value) === null || _debouncedRef$value === void 0 || _debouncedRef$value.call(debouncedRef, () => { _originRunAsync(...args).then(resolve).catch(reject); }); }); onInvalidate(() => { var _debouncedRef$value2; (_debouncedRef$value2 = debouncedRef.value) === null || _debouncedRef$value2 === void 0 || _debouncedRef$value2.cancel(); fetchInstance.runAsync = _originRunAsync; }); } }); if (!(0, vue.unref)(debounceWait)) return {}; return { name: "debouncePlugin", onCancel: () => { var _debouncedRef$value3; (_debouncedRef$value3 = debouncedRef.value) === null || _debouncedRef$value3 === void 0 || _debouncedRef$value3.cancel(); } }; }; var useDebouncePlugin_default = useDebouncePlugin; //#endregion //#region src/plugins/useDevtoolsPlugin.ts const useDevtoolsPlugin = (fetchInstance, { ready = true, debugKey,...rest }) => { const createDevTarget = () => { if (debugKey && !store_default.has(debugKey)) { const functionName = fetchInstance.serviceRef.value.toString().includes("function") ? getFunctionName(fetchInstance.serviceRef.value.toString()) : getArrowFunctionName(fetchInstance.serviceRef.value.toString()); store_default.insert(debugKey, { instance: fetchInstance, requestName: functionName, time: Date.now() }); } }; const processObj = (0, vue.computed)(() => Object.fromEntries(Object.entries({ ready, ...rest }).map(([key, value]) => [key, (0, vue.unref)(value)]))); (0, vue.watchEffect)(() => { if (debugKey && store_default.has(debugKey)) store_default.emit({ ...fetchInstance, options: { ...fetchInstance.options, ...processObj.value } }); }); return { name: "devtoolsPlugin", onBefore: (params) => { createDevTarget(); if (debugKey && store_default.has(debugKey)) store_default.emit({ ...fetchInstance.state, key: debugKey, params, loading: true, time: Date.now(), type: "pending" }); }, onSuccess(data, params) { createDevTarget(); if (debugKey && store_default.has(debugKey)) store_default.emit({ ...fetchInstance.state, key: debugKey, data, params, loading: false, time: Date.now(), type: "done" }); }, onCancel() { createDevTarget(); if (debugKey && store_default.has(debugKey)) store_default.emit({ ...fetchInstance.state, key: debugKey, loading: false, time: Date.now(), type: "cancel" }); }, onError(e, params) { createDevTarget(); if (debugKey && store_default.has(debugKey)) store_default.emit({ ...fetchInstance.state, key: debugKey, params, loading: false, error: e, time: Date.now(), type: "error" }); }, onMutate(data) { createDevTarget(); if (debugKey && store_default.has(debugKey)) store_default.emit({ ...fetchInstance.state, key: debugKey, data, loading: false, time: Date.now(), type: "mutate" }); } }; }; var useDevtoolsPlugin_default = useDevtoolsPlugin; //#endregion //#region src/plugins/useLoadingDelayPlugin.ts const useLoadingDelayPlugin = (inst, { loadingDelay }) => { const delayRef = (0, vue.ref)(); const clear = () => { if (delayRef.value) { clearTimeout((0, vue.unref)(delayRef.value)); delayRef.value = void 0; } }; return { name: "loadingDelayPlugin", onFinally: () => { clear(); const delay = (0, vue.unref)(loadingDelay); /** * * if loadingDelay is set, the loading state will be delayed, * until the delay time is reached. * * if delay is set to 0, the loading state will not be delayed. because 0 is mean nothing. */ if (delay) { inst.setState({ loading: true }); delayRef.value = setTimeout(() => { inst.setState({ loading: false }); }, delay); } }, onError: () => { clear(); } }; }; var useLoadingDelayPlugin_default = useLoadingDelayPlugin; //#endregion //#region src/plugins/usePollingPlugin.ts const usePollingPlugin = (fetchInstance, { pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 }) => { let timeouter; const delayedPolling = (0, vue.ref)(null); const countRef = (0, vue.ref)(0); const isVisible = (0, vue.ref)(false); (0, __dcloudio_uni_app.onPageShow)(() => { isVisible.value = true; if (delayedPolling.value) { delayedPolling.value(); delayedPolling.value = null; } }); (0, __dcloudio_uni_app.onPageHide)(() => { isVisible.value = false; }); const stopPolling = () => { if (timeouter) clearTimeout(timeouter); delayedPolling.value = null; }; (0, vue.watchEffect)(() => { if (!(0, vue.unref)(pollingInterval)) stopPolling(); }); if (!(0, vue.unref)(pollingInterval)) return {}; return { name: "pollingPlugin", onBefore: () => { stopPolling(); }, onError: () => { countRef.value += 1; }, onSuccess: () => { countRef.value = 0; }, onFinally: () => { if (pollingErrorRetryCount === -1 || pollingErrorRetryCount !== -1 && countRef.value <= pollingErrorRetryCount) timeouter = setTimeout(() => { if (!pollingWhenHidden && !isVisible.value) delayedPolling.value = () => { fetchInstance.refresh(); }; else fetchInstance.refresh(); }, (0, vue.unref)(pollingInterval)); else countRef.value = 0; }, onCancel: () => { stopPolling(); } }; }; var usePollingPlugin_default = usePollingPlugin; //#endregion //#region src/plugins/useRetryPlugin.ts const useRetryPlugin = (fetchInstance, { retryInterval, retryCount }) => { const timerRef = (0, vue.ref)(); const countRef = (0, vue.ref)(0); const triggerByRetry = (0, vue.ref)(false); if (!retryCount) return {}; return { name: "retryPlugin", 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) { const timeout = retryInterval !== null && retryInterval !== void 0 ? retryInterval : Math.min(1e3 * 2 ** countRef.value, 3e4); timerRef.value = setTimeout(() => { triggerByRetry.value = true; fetchInstance.refresh(); }, timeout); } else countRef.value = 0; }, onCancel: () => { countRef.value = 0; if (timerRef.value) clearTimeout(timerRef.value); } }; }; var useRetryPlugin_default = useRetryPlugin; //#endregion //#region src/plugins/useThrottlePlugin.ts const useThrottlePlugin = (fetchInstance, { throttleWait, throttleLeading, throttleTrailing }) => { const options = (0, vue.computed)(() => { const ret = { delay: 200 }; if ((0, vue.unref)(throttleWait) !== void 0) ret.delay = (0, vue.unref)(throttleWait) || 200; if ((0, vue.unref)(throttleLeading) !== void 0) ret.leading = (0, vue.unref)(throttleLeading); if ((0, vue.unref)(throttleTrailing) !== void 0) ret.trailing = (0, vue.unref)(throttleTrailing); return ret; }); const throttledRef = (0, vue.computed)(() => (0, __caikengren_uni_hooks_shared.createFilterWrapper)((0, __caikengren_uni_hooks_shared.throttleFilter)(options.value), (callback) => { callback(); })); (0, vue.watchEffect)((onInvalidate) => { if ((0, vue.unref)(throttleWait)) { const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance); fetchInstance.runAsync = (...args) => new Promise((resolve, reject) => { var _throttledRef$value; (_throttledRef$value = throttledRef.value) === null || _throttledRef$value === void 0 || _throttledRef$value.call(throttledRef, () => { _originRunAsync(...args).then(resolve).catch(reject); }); }); onInvalidate(() => { var _throttledRef$value2; fetchInstance.runAsync = _originRunAsync; (_throttledRef$value2 = throttledRef.value) === null || _throttledRef$value2 === void 0 || _throttledRef$value2.cancel(); }); } }); if (!(0, vue.unref)(throttleWait)) return {}; return { name: "throttlePlugin", onCancel: () => { var _throttledRef$value3; (_throttledRef$value3 = throttledRef.value) === null || _throttledRef$value3 === void 0 || _throttledRef$value3.cancel(); } }; }; var useThrottlePlugin_default = useThrottlePlugin; //#endregion //#region src/config.ts const USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY = Symbol("USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY"); //#endregion //#region src/utils/index.ts const isFunction = (value) => typeof value === "function"; const isBoolean = (value) => typeof value === "boolean"; //#endregion //#region src/Fetch.ts var Fetch = class { constructor(serviceRef, options, setUpdateData, initState = {}) { this.serviceRef = serviceRef; this.options = options; this.setUpdateData = setUpdateData; this.initState = initState; this.count = 0; this.state = { loading: false, params: void 0, data: void 0, error: void 0 }; this.previousValidData = void 0; this.state = { ...this.state, loading: !options.manual, ...initState }; } /** * set state * @param currentState currentState */ setState(currentState = {}) { this.state = { ...this.state, ...currentState }; this.setUpdateData(this.state); } /** * * @param data Result value `unknown` * @param key Result key `data`| `params` | `loading`| `error` */ setFetchState(data, key) { if (Array.isArray(key)) key.forEach((k) => { this.state[k] = data; this.setUpdateData(data, k); }); else { this.state[key] = data; this.setUpdateData(data, key); } } /** * Traverse the plugin that needs to be run, * 插件的回调函数, 用于执行插件的逻辑. */ runPluginHandler(event, ...rest) { var _ref, _this$pluginImpls$map, _this$pluginImpls; const r = (_ref = (_this$pluginImpls$map = (_this$pluginImpls = this.pluginImpls) === null || _this$pluginImpls === void 0 ? void 0 : _this$pluginImpls.map((i) => { var _i$event; return (_i$event = i[event]) === null || _i$event === void 0 ? void 0 : _i$event.call(i, ...rest); })) !== null && _this$pluginImpls$map !== void 0 ? _this$pluginImpls$map : []) === null || _ref === void 0 ? void 0 : _ref.filter(Boolean); return Object.assign({}, ...r); } async runAsync(...params) { this.count += 1; const currentCount = this.count; const { stopNow = false, returnNow = false,...state } = this.runPluginHandler("onBefore", params); if (stopNow) return new Promise(() => {}); this.setState({ loading: true, params, ...state }); if (returnNow) return Promise.resolve(state.data); try { var _this$options$onBefor, _this$options; (_this$options$onBefor = (_this$options = this.options).onBefore) === null || _this$options$onBefor === void 0 || _this$options$onBefor.call(_this$options, params); } catch (error) { var _this$options$onError, _this$options2; this.setState({ error, loading: false }); (_this$options$onError = (_this$options2 = this.options).onError) === null || _this$options$onError === void 0 || _this$options$onError.call(_this$options2, error, params); this.runPluginHandler("onError", error, params); return new Promise(() => {}); } try { let { servicePromise } = this.runPluginHandler("onRequest", this.serviceRef.value, params); const requestReturnResponse = (res) => { var _this$options$onSucce, _this$options3, _this$options$onFinal, _this$options4; if (currentCount !== this.count) return new Promise(() => {}); const formattedResult = this.options.formatResult ? this.options.formatResult(res) : res; this.setState({ data: formattedResult, error: void 0, loading: false }); (_this$options$onSucce = (_this$options3 = this.options).onSuccess) === null || _this$options$onSucce === void 0 || _this$options$onSucce.call(_this$options3, formattedResult, params); this.runPluginHandler("onSuccess", formattedResult, params); this.previousValidData = formattedResult; (_this$options$onFinal = (_this$options4 = this.options).onFinally) === null || _this$options$onFinal === void 0 || _this$options$onFinal.call(_this$options4, params, formattedResult, void 0); if (currentCount === this.count) this.runPluginHandler("onFinally", params, formattedResult, void 0); return formattedResult; }; if (!servicePromise) servicePromise = this.serviceRef.value(...params); return requestReturnResponse(await servicePromise); } catch (error) { var _this$options$onError2, _this$options5, _this$options6, _this$options7, _this$options8, _this$options$onFinal2, _this$options9; if (currentCount !== this.count) return new Promise(() => {}); this.setState({ error, loading: false }); (_this$options$onError2 = (_this$options5 = this.options).onError) === null || _this$options$onError2 === void 0 || _this$options$onError2.call(_this$options5, error, params); this.runPluginHandler("onError", error, params); if (isFunction((_this$options6 = this.options) === null || _this$options6 === void 0 ? void 0 : _this$options6.rollbackOnError) && ((_this$options7 = this.options) === null || _this$options7 === void 0 ? void 0 : _this$options7.rollbackOnError(params)) || isBoolean((_this$options8 = this.options) === null || _this$options8 === void 0 ? void 0 : _this$options8.rollbackOnError) && this.options.rollbackOnError) this.setState({ data: this.previousValidData }); (_this$options$onFinal2 = (_this$options9 = this.options).onFinally) === null || _this$options$onFinal2 === void 0 || _this$options$onFinal2.call(_this$options9, params, void 0, error); if (currentCount === this.count) this.runPluginHandler("onFinally", params, void 0, error); throw error; } } run(...params) { this.runAsync(...params).catch((error) => { if (!this.options.onError) console.error(error); }); } cancel() { this.count += 1; this.setState({ loading: false }); this.runPluginHandler("onCancel"); } refresh() { this.run(...this.state.params || []); } refreshAsync() { return this.runAsync(...this.state.params || []); } mutate(data) { const targetData = isFunction(data) ? data(this.state.data) : data; this.runPluginHandler("onMutate", targetData); this.setState({ data: targetData }); } }; //#endregion //#region src/useRequestImplement.ts function isUseRequestFetchState(state) { return Object.keys(state).filter((i) => [ "data", "loading", "params", "error" ].includes(i)).length === 4; } function useRequestImplement(service, options = {}, plugins = []) { const USEREQUEST_GLOBAL_OPTIONS = (0, vue.inject)(USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY, {}); const { initialData = void 0, manual = false, ready = true,...rest } = { ...USEREQUEST_GLOBAL_OPTIONS !== null && USEREQUEST_GLOBAL_OPTIONS !== void 0 ? USEREQUEST_GLOBAL_OPTIONS : {}, ...options !== null && options !== void 0 ? options : {} }; const fetchOptions = { manual, ready, initialData, ...rest }; const serviceRef = (0, vue.ref)(service); const state = (0, vue.reactive)({ data: initialData, loading: false, params: void 0, error: void 0 }); const setState = (currentState, field) => { if (field) state[field] = currentState; else if (isUseRequestFetchState(currentState)) { state.data = currentState.data; state.loading = currentState.loading; state.error = currentState.error; state.params = currentState.params; } }; const initState = plugins.map((p) => { var _p$onInit; return p === null || p === void 0 || (_p$onInit = p.onInit) === null || _p$onInit === void 0 ? void 0 : _p$onInit.call(p, fetchOptions); }).filter(Boolean); const fetchInstance = new Fetch(serviceRef, fetchOptions, setState, Object.assign({}, ...initState, state)); fetchInstance.options = fetchOptions; fetchInstance.pluginImpls = plugins.map((p) => p(fetchInstance, fetchOptions)); const readyComputed = (0, vue.computed)(() => (0, vue.isRef)(ready) ? ready.value : ready); (0, vue.watchEffect)(() => { if (!manual) { const params = fetchInstance.state.params || options.defaultParams || []; if (readyComputed.value && fetchInstance.options.refreshDeps === true && !!serviceRef.value) fetchInstance.run(...params); } }); if (!manual && fetchInstance.options.refreshDeps !== true) { const params = fetchInstance.state.params || options.defaultParams || []; if ((0, vue.unref)(ready)) fetchInstance.run(...params); } (0, vue.onScopeDispose)(() => { fetchInstance.cancel(); }); return { ...(0, vue.toRefs)(state), cancel: fetchInstance.cancel.bind(fetchInstance), refresh: fetchInstance.refresh.bind(fetchInstance), refreshAsync: fetchInstance.refreshAsync.bind(fetchInstance), run: fetchInstance.run.bind(fetchInstance), runAsync: fetchInstance.runAsync.bind(fetchInstance), mutate: fetchInstance.mutate.bind(fetchInstance) }; } var useRequestImplement_default = useRequestImplement; //#endregion //#region src/utils/resolve-args.ts function withArgs(hook, use) { return function useRequestArgs(service, options = {}, plugins = []) { let next = hook; const middleware = use || []; for (let i = middleware.length; i--;) next = middleware[i](next); return next(service, options, plugins); }; } //#endregion //#region src/useRequest.ts function useRequest(service, options, plugins) { var _ref; const BuiltInPlugins = (_ref = [ useDevtoolsPlugin_default, useDebouncePlugin_default, useLoadingDelayPlugin_default, usePollingPlugin_default, useThrottlePlugin_default, useAutoRunPlugin_default, useCachePlugin_default, useRetryPlugin_default ]) === null || _ref === void 0 ? void 0 : _ref.filter(Boolean); return withArgs(useRequestImplement_default, options === null || options === void 0 ? void 0 : options.use)(service, options, [...plugins || [], ...BuiltInPlugins]); } var useRequest_default = useRequest; //#endregion //#region src/useRequestProvider.ts function useRequestProvider(config) { (0, vue.provide)(USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY, config); } //#endregion //#region src/index.ts var src_default = useRequest_default; //#endregion exports.clearUseRequestCache = clearCache; exports.default = src_default; exports.useRequestDevToolsPlugin = devtools_default; exports.useRequestProvider = useRequestProvider; })(this.UniHooks = this.UniHooks || {}, __vue_devtools_api, Vue, __caikengren_uni_hooks_shared, __dcloudio_uni_app);