53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
![]() |
// import { useAuthStore } from "~/stores/authStore";
|
||
|
import { useStorage } from "@vueuse/core";
|
||
|
|
||
|
export default defineNuxtPlugin((nuxtApp) => {
|
||
|
let token = useStorage("id_token", "GuestAccess").value;
|
||
|
|
||
|
const api = $fetch.create({
|
||
|
onRequest({ request, options, error }) {
|
||
|
options.baseURL =
|
||
|
import.meta.env.VITE_BASE_URL +
|
||
|
import.meta.env.VITE_API_NAME +
|
||
|
options.baseURL;
|
||
|
|
||
|
if (token) {
|
||
|
const headers = (options.headers ||= {});
|
||
|
if (Array.isArray(headers)) {
|
||
|
headers.push(["Authorization", token]);
|
||
|
} else if (headers instanceof Headers) {
|
||
|
headers.set("Authorization", token);
|
||
|
} else {
|
||
|
headers.Authorization = token;
|
||
|
}
|
||
|
}
|
||
|
},
|
||
|
async onResponseError({ response }) {
|
||
|
if (response.status === 401) {
|
||
|
await nuxtApp.runWithContext(() => navigateTo("/login"));
|
||
|
}
|
||
|
},
|
||
|
onRequestError({ request, options, error }) {
|
||
|
// Handle the request errors
|
||
|
},
|
||
|
onResponse({ request, response, options }) {
|
||
|
// Process the response data
|
||
|
},
|
||
|
});
|
||
|
|
||
|
// Add custom methods for GET, POST, and DELETE
|
||
|
const http = {
|
||
|
getRequest: (url, options = {}) => api(url, { method: "GET", ...options }),
|
||
|
postRequest: (url, body, options = {}) =>
|
||
|
api(url, { method: "POST", body, ...options }),
|
||
|
deleteRequest: (url, options = {}) => api(url, { method: "DELETE", ...options }),
|
||
|
};
|
||
|
|
||
|
// Expose to useNuxtApp().$api and useNuxtApp().$http
|
||
|
return {
|
||
|
provide: {
|
||
|
http
|
||
|
},
|
||
|
};
|
||
|
});
|