Many fix and improvements
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
import axios from "axios";
|
||||
import {inject} from "vue";
|
||||
import axios from "axios"
|
||||
import {useAuthStore} from "@/stores/authStore.js"
|
||||
|
||||
const key = Symbol("api");
|
||||
|
||||
export default function(app) {
|
||||
export function useClient() {
|
||||
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
|
||||
@@ -13,23 +11,16 @@ export default function(app) {
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const requestInterceptor = (config) => {
|
||||
const token = localStorage.getItem("jwt");
|
||||
if (token) config.headers["Authorization"] = `Bearer ${token}`;
|
||||
return config;
|
||||
if (authStore.isAuthenticated) {
|
||||
config.headers["Authorization"] = `Bearer ${authStore.accessToken}`
|
||||
}
|
||||
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