httpClient.ts
1,639 bytes
| 1 | import axios from 'axios' |
|---|---|
| 2 | import { useAuthStore } from '@/stores/auth' |
| 3 | import { useLangStore } from '@/stores/lang' |
| 4 | import AccountService from '@/services/AccountService' |
| 5 | import router from '@/router' |
| 6 | |
| 7 | const httpClient = axios.create({ |
| 8 | baseURL: import.meta.env.VITE_API_BASE_URL, |
| 9 | }) |
| 10 | |
| 11 | httpClient.interceptors.request.use((config) => { |
| 12 | const authStore = useAuthStore() |
| 13 | if (authStore.jwt) { |
| 14 | config.headers.Authorization = `Bearer ${authStore.jwt}` |
| 15 | } |
| 16 | const langStore = useLangStore() |
| 17 | config.headers['Accept-Language'] = langStore.currentLocale |
| 18 | return config |
| 19 | }) |
| 20 | |
| 21 | httpClient.interceptors.response.use( |
| 22 | (response) => response, |
| 23 | async (error) => { |
| 24 | const originalRequest = error.config |
| 25 | |
| 26 | if (error.response?.status === 401 && !originalRequest._retry) { |
| 27 | originalRequest._retry = true |
| 28 | |
| 29 | const authStore = useAuthStore() |
| 30 | if (authStore.jwt && authStore.refreshToken) { |
| 31 | const result = await AccountService.refreshTokenAsync( |
| 32 | authStore.jwt, |
| 33 | authStore.refreshToken, |
| 34 | ) |
| 35 | |
| 36 | if (result.data) { |
| 37 | authStore.jwt = result.data.jwt |
| 38 | authStore.refreshToken = result.data.refreshToken |
| 39 | authStore.userName = `${result.data.firstName} ${result.data.lastName}` |
| 40 | |
| 41 | originalRequest.headers.Authorization = `Bearer ${result.data.jwt}` |
| 42 | return httpClient(originalRequest) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | if (authStore.refreshToken) { |
| 47 | await AccountService.logoutAsync(authStore.refreshToken) |
| 48 | } |
| 49 | authStore.logout() |
| 50 | await router.push({ name: 'Login' }) |
| 51 | } |
| 52 | |
| 53 | return Promise.reject(error) |
| 54 | }, |
| 55 | ) |
| 56 | |
| 57 | export default httpClient |
| 58 | |