UNPKG

vue-hooks-plus

Version:
87 lines (86 loc) 2.93 kB
"use strict"; const vue = require("vue"); const Fetch = require("./Fetch"); const config = require("./config"); const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e }; const Fetch__default = /* @__PURE__ */ _interopDefaultLegacy(Fetch); function isUseRequestFetchState(state) { const keys = Object.keys(state); return keys.filter((i) => ["data", "loading", "params", "error"].includes(i)).length === 4; } function useRequestImplement(service, options = {}, plugins = []) { const USEREQUEST_GLOBAL_OPTIONS = vue.inject( config.USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY, {} ); const { initialData = void 0, manual = false, ready = true, ...rest } = { ...USEREQUEST_GLOBAL_OPTIONS != null ? USEREQUEST_GLOBAL_OPTIONS : {}, ...options != null ? options : {} }; const fetchOptions = { manual, ready, initialData, ...rest }; const serviceRef = vue.ref(service); const state = 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 _a; return (_a = p == null ? void 0 : p.onInit) == null ? void 0 : _a.call(p, fetchOptions); }).filter(Boolean); const fetchInstance = new Fetch__default.default( serviceRef, fetchOptions, setState, Object.assign({}, ...initState, state) ); fetchInstance.options = fetchOptions; fetchInstance.pluginImpls = plugins.map((p) => { return p(fetchInstance, fetchOptions); }); const readyComputed = vue.computed(() => vue.isRef(ready) ? ready.value : ready); 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 (vue.unref(ready)) fetchInstance.run(...params); } vue.onScopeDispose(() => { fetchInstance.cancel(); }); return { ...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) }; } module.exports = useRequestImplement;