You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.5 KiB
75 lines
2.5 KiB
import {
|
|
Configuration,
|
|
ArticleApi,
|
|
ArticleAdminApi,
|
|
AuthApi,
|
|
TagApi,
|
|
TagAdminApi,
|
|
MediaApi,
|
|
SearchApi,
|
|
PublicApi,
|
|
UserApi,
|
|
CommentApi,
|
|
CommentAdminApi
|
|
} from '@/generated/api'
|
|
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios'
|
|
|
|
const axiosInstance = axios.create({
|
|
baseURL: '/',
|
|
timeout: 10000
|
|
})
|
|
|
|
type RetryableRequestConfig = InternalAxiosRequestConfig & { _retry?: boolean }
|
|
|
|
// 请求拦截:自动带 Access Token
|
|
axiosInstance.interceptors.request.use((config) => {
|
|
const token = localStorage.getItem('token')
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
}
|
|
return config
|
|
})
|
|
|
|
// 响应拦截:401 静默刷新 Token
|
|
axiosInstance.interceptors.response.use(
|
|
(res) => res,
|
|
async (err: AxiosError) => {
|
|
const original = err.config as RetryableRequestConfig | undefined
|
|
if (err.response?.status === 401 && original && !original._retry && !original.url?.includes('/auth/login')) {
|
|
original._retry = true
|
|
const refresh = localStorage.getItem('refreshToken')
|
|
if (refresh) {
|
|
try {
|
|
const authApi = new AuthApi(new Configuration(), '', axiosInstance)
|
|
const resp = await authApi.apiAuthRefreshPost({ refreshToken: refresh })
|
|
const data = resp.data.data!
|
|
localStorage.setItem('token', data.accessToken)
|
|
localStorage.setItem('refreshToken', data.refreshToken)
|
|
original.headers.Authorization = `Bearer ${data.accessToken}`
|
|
return axiosInstance(original)
|
|
} catch {
|
|
localStorage.removeItem('token')
|
|
localStorage.removeItem('refreshToken')
|
|
window.location.href = '/login'
|
|
}
|
|
} else {
|
|
window.location.href = '/login'
|
|
}
|
|
}
|
|
return Promise.reject(err)
|
|
}
|
|
)
|
|
|
|
const config = new Configuration()
|
|
|
|
export const articleApi = new ArticleApi(config, '', axiosInstance)
|
|
export const articleAdminApi = new ArticleAdminApi(config, '', axiosInstance)
|
|
export const authApi = new AuthApi(config, '', axiosInstance)
|
|
export const tagApi = new TagApi(config, '', axiosInstance)
|
|
export const tagAdminApi = new TagAdminApi(config, '', axiosInstance)
|
|
export const mediaApi = new MediaApi(config, '', axiosInstance)
|
|
export const searchApi = new SearchApi(config, '', axiosInstance)
|
|
export const publicApi = new PublicApi(config, '', axiosInstance)
|
|
export const userApi = new UserApi(config, '', axiosInstance)
|
|
export const commentApi = new CommentApi(config, '', axiosInstance)
|
|
export const commentAdminApi = new CommentAdminApi(config, '', axiosInstance)
|