Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RondaYummy/cf8e168d57d11a6fa9c1bcfd59dda0b3 to your computer and use it in GitHub Desktop.
Save RondaYummy/cf8e168d57d11a6fa9c1bcfd59dda0b3 to your computer and use it in GitHub Desktop.
api-module
import { ref } from 'vue';
import HTTPService from '../services/http/HTTPService';
// також просто як приклад, що звідси можна глобально викликати стан завантаження сторінки з Квазару.
import { Loading } from 'quasar';
export function useAPI(url, ...args) {
let config = {};
let start = true;
// тут ми просто створюємо інстанс axios, додаємо інтерцептори та інше, що необхідно
const instance = HTTPService();
if (args.length > 0) {
/**
* Unable to use `instanceof` here because of (https://github.com/axios/axios/issues/737)
* so instead we are checking if there is a `requset` on the object to see if it is an
* axios instance
*/
if (typeof args[0] === 'boolean') {
start = args[0];
} else {
config = args[0];
}
}
if (args.length > 1) {
start = args[1];
}
const response = ref;
const data = ref(undefined);
const loading = ref(false);
const finished = ref(false);
const error = ref();
const execute = (localConfig = {}) => {
config = {
...config,
...localConfig,
};
Loading.show();
loading.value = true;
data.value = undefined;
return instance(config.url || url, config)
.then((r) => {
response.value = r;
data.value = config.parseResponse
? config.parseResponse(r.data)
: r.data;
return data.value;
})
.catch((err) => {
error.value = err.response;
if (!error.value) {
return;
}
// Люба логіка для відловлення помилок авторизації, наприклад, це не важливл
if (error.value?.data?.message === 'Invalid refresh') {
return err;
}
return err;
})
.finally(() => {
loading.value = false;
finished.value = true;
Loading.hide();
});
};
if (start) {
execute();
}
return {
execute,
response,
loading,
finished,
data,
error,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment