UNPKG

@vue-composable/axios

Version:
96 lines (88 loc) 3.55 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var axios = require('axios'); var vueComposable = require('vue-composable'); var compositionApi = require('@vue/composition-api'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; } var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios); function makeAxios(client, throwException = false) { const isCancelled = compositionApi.ref(false); const cancelledMessage = compositionApi.ref(null); let cancelToken = undefined; const cancel = (message) => { if (!cancelToken) { /* istanbul ignore else */ { throw new Error("Cannot cancel because no request has been made"); } } cancelToken.cancel(message); isCancelled.value = true; cancelledMessage.value = message; }; const use = vueComposable.usePromise(async (request) => { cancelToken = axios__default.CancelToken.source(); isCancelled.value = false; cancelledMessage.value = null; const opts = vueComposable.isString(request) ? { url: request } : request; return client.request({ cancelToken: cancelToken.token, ...opts }); }, { lazy: true, throwException }); const data = compositionApi.computed(() => (use.result.value && use.result.value.data) || (use.error.value && use.error.value.response && use.error.value.response.data) || null); const status = compositionApi.computed(() => (use.result.value && use.result.value.status) || (use.error.value && use.error.value.response && use.error.value.response.status) || null); const statusText = compositionApi.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 */ !axios__default && console.warn(`[axios] not installed, please install it`); const config = !vueComposable.isString(configUrlThrowException) && !vueComposable.isBoolean(configUrlThrowException) ? configUrlThrowException : vueComposable.isObject(configThrowException) ? configThrowException : undefined; throwException = vueComposable.isBoolean(configUrlThrowException) ? configUrlThrowException : vueComposable.isBoolean(configThrowException) ? configThrowException : throwException; const axiosClient = axios__default.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; } exports.makeAxios = makeAxios; exports.useAxios = useAxios;