Created
April 1, 2025 17:35
-
-
Save RondaYummy/cf8e168d57d11a6fa9c1bcfd59dda0b3 to your computer and use it in GitHub Desktop.
api-module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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