@vue-composable/axios
Version:
@vue-composable/axios
90 lines (86 loc) • 3.22 kB
JavaScript
import axios from 'axios';
import { usePromise, isString, isBoolean, isObject } from 'vue-composable';
import { ref, computed } from 'vue';
function makeAxios(client, throwException = false) {
const isCancelled = ref(false);
const cancelledMessage = ref(null);
let cancelToken = undefined;
const cancel = (message) => {
if (!cancelToken) {
/* istanbul ignore else */
if ((process.env.NODE_ENV !== 'production')) {
throw new Error("Cannot cancel because no request has been made");
}
else {
return;
}
}
cancelToken.cancel(message);
isCancelled.value = true;
cancelledMessage.value = message;
};
const use = usePromise(async (request) => {
cancelToken = axios.CancelToken.source();
isCancelled.value = false;
cancelledMessage.value = null;
const opts = isString(request) ? { url: request } : request;
return client.request({
cancelToken: cancelToken.token,
...opts
});
}, {
lazy: true,
throwException
});
const data = computed(() => (use.result.value && use.result.value.data) ||
(use.error.value &&
use.error.value.response &&
use.error.value.response.data) ||
null);
const status = computed(() => (use.result.value && use.result.value.status) ||
(use.error.value &&
use.error.value.response &&
use.error.value.response.status) ||
null);
const statusText = computed(() => (use.result.value && use.result.value.statusText) ||
(use.error.value &&
use.error.value.response &&
use.error.value.response.statusText) ||
null);
return {
...use,
client,
data,
status,
statusText,
cancel,
isCancelled,
cancelledMessage
};
}
function useAxios(configUrlThrowException, configThrowException, throwException = false) {
/* istanbul ignore next */
(process.env.NODE_ENV !== 'production') && !axios && console.warn(`[axios] not installed, please install it`);
const config = !isString(configUrlThrowException) && !isBoolean(configUrlThrowException)
? configUrlThrowException
: isObject(configThrowException)
? configThrowException
: undefined;
throwException = isBoolean(configUrlThrowException)
? configUrlThrowException
: isBoolean(configThrowException)
? configThrowException
: throwException;
const axiosClient = axios.create(config);
const use = makeAxios(axiosClient, throwException);
// if url provided in the config, execute it straight away
// NOTE: `false` is passed to the `exec` to prevent the exception to be thrown
if (typeof configUrlThrowException === "string") {
use.exec({ ...config, url: configUrlThrowException }, false);
}
else if (config && config.url) {
use.exec(config, false);
}
return use;
}
export { makeAxios, useAxios };