Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // plugins/nuxt/axios.ts
- import type { AxiosInstance, AxiosError } from 'axios';
- import type { Context } from '@nuxt/types';
- // @ts-ignore
- import isAbsoluteURL from 'axios/lib/helpers/isAbsoluteURL';
- import { axios, axiosStatic, withCredentials } from '@monq/core/src/lib/axios';
- // source: https://github.com/nuxt-community/axios-module/blob/85840c6b087c1b250e9d930f3db44c5fd5f41d59/lib/plugin.js#L116
- const setupNuxtProgress = (axiosInstance: AxiosInstance) => {
- if (typeof window === 'undefined') {
- return;
- }
- // A noop loading inteterface for when $nuxt is not yet ready
- const noopLoading = {
- finish: () => { },
- start: () => { },
- fail: () => { },
- set: () => { },
- };
- const $loading = () => {
- const $nuxt = typeof window !== 'undefined' && window.$nuxt;
- return ($nuxt && $nuxt.$loading && $nuxt.$loading.hasOwnProperty('set')) ? $nuxt.$loading : noopLoading;
- };
- let currentRequests = 0;
- axiosInstance.interceptors.request.use((config) => {
- currentRequests++;
- return config;
- });
- axiosInstance.interceptors.response.use((response) => {
- currentRequests--;
- if (currentRequests <= 0) {
- currentRequests = 0;
- $loading().finish();
- }
- return response;
- });
- const onError = (error: AxiosError) => {
- currentRequests--;
- if (axiosStatic.isCancel(error)) {
- if (currentRequests <= 0) {
- currentRequests = 0;
- $loading().finish();
- }
- return Promise.reject(error);
- }
- // @ts-ignore
- $loading().fail();
- $loading().finish();
- return Promise.reject(error);
- };
- axiosInstance.interceptors.request.use(undefined, onError);
- axiosInstance.interceptors.response.use(undefined, onError);
- const onProgress = (e: { loaded: number, total: number }) => {
- if (!currentRequests) {
- return;
- }
- const progress = ((e.loaded * 100) / (e.total * currentRequests));
- // @ts-ignore
- $loading().set(Math.min(100, progress));
- };
- axiosInstance.defaults.onUploadProgress = onProgress;
- axiosInstance.defaults.onDownloadProgress = onProgress;
- };
- export default function({ $config }: Context) {
- // apply interceptors on response
- axios.interceptors.request.use(withCredentials);
- setupNuxtProgress(axios);
- const defaults = axios.defaults;
- defaults.baseURL = $config.BASE_API_URL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement