Refactor!: Codebase
This commit is contained in:
35
src/plugins/api.js
Normal file
35
src/plugins/api.js
Normal 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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user