vue-hooks-plus
Version:
Vue hooks library
86 lines (85 loc) • 2.79 kB
JavaScript
import { inject, ref, reactive, computed, isRef, watchEffect, unref, onScopeDispose, toRefs } from "vue";
import Fetch from "./Fetch";
import { USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY } from "./config";
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 = inject(
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 = ref(service);
const state = 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(
serviceRef,
fetchOptions,
setState,
Object.assign({}, ...initState, state)
);
fetchInstance.options = fetchOptions;
fetchInstance.pluginImpls = plugins.map((p) => {
return p(fetchInstance, fetchOptions);
});
const readyComputed = computed(() => isRef(ready) ? ready.value : ready);
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 (unref(ready))
fetchInstance.run(...params);
}
onScopeDispose(() => {
fetchInstance.cancel();
});
return {
...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)
};
}
export {
useRequestImplement as default
};