98 lines
3.4 KiB
TypeScript
98 lines
3.4 KiB
TypeScript
import axios from 'axios'
|
||
import { goLogin } from '../utils/navigate'
|
||
import { currentLocale, hasTranslation, translate } from '../i18n'
|
||
import {
|
||
authStorageKeys,
|
||
clearAuthSession,
|
||
markActivity,
|
||
refreshAuthSession,
|
||
refreshIfNeeded,
|
||
} from '../auth/session'
|
||
|
||
declare module 'axios' {
|
||
export interface AxiosRequestConfig {
|
||
// Public kiosk pages must remain usable when this browser has an expired login session.
|
||
skipAuthSession?: boolean
|
||
}
|
||
}
|
||
|
||
const http = axios.create({
|
||
baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api',
|
||
timeout: 15000,
|
||
})
|
||
|
||
function isAuthenticationRequest(url?: string) {
|
||
return url?.startsWith('/auth/login') ||
|
||
url?.endsWith('/auth/refresh') ||
|
||
url?.endsWith('/auth/logout') ||
|
||
url?.endsWith('/auth/sso/exchange') ||
|
||
url?.endsWith('/auth/sso/bind')
|
||
}
|
||
|
||
http.interceptors.request.use(async (config) => {
|
||
config.headers['Accept-Language'] = currentLocale.value
|
||
if (!isAuthenticationRequest(config.url) && !config.skipAuthSession) {
|
||
const activeToken = await refreshIfNeeded(true)
|
||
if (activeToken) markActivity()
|
||
}
|
||
const token = localStorage.getItem(authStorageKeys.token)
|
||
if (token && !config.skipAuthSession) config.headers.Authorization = `Bearer ${token}`
|
||
return config
|
||
})
|
||
|
||
http.interceptors.response.use(
|
||
(response) => response,
|
||
async (error) => {
|
||
const authenticationRequest = isAuthenticationRequest(error.config?.url)
|
||
const retryableConfig = error.config as
|
||
(typeof error.config & { _jiaowuRetried?: boolean }) | undefined
|
||
if (error.response?.status === 401 && !authenticationRequest && !error.config?.skipAuthSession &&
|
||
!retryableConfig?._jiaowuRetried) {
|
||
const token = await refreshAuthSession()
|
||
if (token && retryableConfig) {
|
||
retryableConfig._jiaowuRetried = true
|
||
retryableConfig.headers.Authorization = `Bearer ${token}`
|
||
return http.request(retryableConfig)
|
||
}
|
||
}
|
||
if (error.response?.status === 401 && !authenticationRequest && !error.config?.skipAuthSession) {
|
||
clearAuthSession()
|
||
goLogin()
|
||
}
|
||
return Promise.reject(error)
|
||
},
|
||
)
|
||
|
||
export function apiErrorMessage(error: unknown) {
|
||
if (!axios.isAxiosError(error)) return translate('errors.generic')
|
||
const status = error.response?.status
|
||
const data = error.response?.data
|
||
const code = typeof data?.code === 'string' ? data.code.trim() : ''
|
||
const codeKey = code ? `api.${code}` : ''
|
||
if (codeKey && hasTranslation(codeKey)) {
|
||
const args = data?.args && typeof data.args === 'object' ? data.args : undefined
|
||
return translate(codeKey, args)
|
||
}
|
||
const message = typeof data?.message === 'string' ? data.message.trim() : ''
|
||
if (message) return message
|
||
if (data?.errors && typeof data.errors === 'object') {
|
||
const validationMessage = Object.values(data.errors)
|
||
.flat()
|
||
.map((item) => String(item).trim())
|
||
.filter(Boolean)
|
||
.join(';')
|
||
if (validationMessage) return validationMessage
|
||
}
|
||
const detail = typeof data?.detail === 'string' ? data.detail.trim() : ''
|
||
if (detail) return detail
|
||
const title = typeof data?.title === 'string' ? data.title.trim() : ''
|
||
if (title) return title
|
||
if (status === 403) return translate('errors.forbidden')
|
||
if (status === 404) return translate('errors.notFound')
|
||
if (status === 401) return translate('errors.unauthorized')
|
||
if (status && status >= 500) return translate('errors.server')
|
||
return translate('errors.network')
|
||
}
|
||
|
||
export default http
|