40 lines
1.0 KiB
TypeScript
40 lines
1.0 KiB
TypeScript
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
|
|
import { mapState } from 'pinia'
|
|
import type { Logger } from 'pino'
|
|
import { useUserStore } from '~/stores/user'
|
|
export default defineNuxtPlugin(() => {
|
|
if (useRuntimeConfig().public.apiUrl === '') {
|
|
throw new Error('Please ensure that the apiUrl is set in .env File.')
|
|
}
|
|
const defaultUrl = useRuntimeConfig().public.apiUrl
|
|
|
|
|
|
// Access Pinia state
|
|
// @ts-ignore
|
|
const api: AxiosInstance = axios.create({
|
|
// @ts-ignore
|
|
baseURL: defaultUrl,
|
|
headers: {
|
|
common: {}
|
|
},
|
|
withCredentials: true
|
|
})
|
|
// @ts-ignore
|
|
api.interceptors.request.use((config: AxiosRequestConfig) => {
|
|
|
|
|
|
const logger = useNuxtApp().$logger as any
|
|
logger.info("BACKEND URL "+ defaultUrl)
|
|
config.baseURL = defaultUrl
|
|
const token = mapState(useUserStore, ['token']).token()
|
|
// @ts-ignore
|
|
config.headers.Authorization = 'Bearer ' + token
|
|
return config
|
|
})
|
|
return {
|
|
provide: {
|
|
axios: api
|
|
}
|
|
}
|
|
})
|