Refactor!: Codebase

This commit is contained in:
Kamigen
2024-03-30 21:35:19 -04:00
parent af35da4557
commit abab4587d1
11 changed files with 64 additions and 66 deletions

35
src/plugins/api.js Normal file
View File

@@ -0,0 +1,35 @@
import axios from "axios";
import {inject} from "vue";
const key = Symbol("api");
export default function(app) {
if (!import.meta.env.VITE_API_URL) throw new Error("VITE_API_URL is not provided")
// You create a .env.development file and a .env file
// depending on the environment, the correct file will be used
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 2000,
});
const requestInterceptor = (config) => {
const token = localStorage.getItem("jwt");
if (token) config.headers["Authorization"] = `Bearer ${token}`;
return config;
}
api.interceptors.request.use(requestInterceptor);
// This is a local injection, to use it in your components you can do this:
// const api = inject("api")
// api.get("/some-endpoint")
app.provide(key, api)
}
export function useClient() {
const api = inject(key)
if (!api) throw new Error("api is not provided")
return api;
}