2024-03-26 11:47:11 +08:00
|
|
|
import type { AxiosRequestConfig } from 'axios';
|
|
|
|
import { useAuthStore } from '@/store/modules/auth';
|
|
|
|
import { localStg } from '@/utils/storage';
|
|
|
|
import { fetchRefreshToken } from '../api';
|
2024-05-08 11:57:58 +08:00
|
|
|
import type { RequestInstanceState } from './type';
|
2024-03-26 11:47:11 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* refresh token
|
|
|
|
*
|
|
|
|
* @param axiosConfig - request config when the token is expired
|
|
|
|
*/
|
|
|
|
export async function handleRefreshToken(axiosConfig: AxiosRequestConfig) {
|
|
|
|
const { resetStore } = useAuthStore();
|
|
|
|
|
|
|
|
const refreshToken = localStg.get('refreshToken') || '';
|
|
|
|
const { error, data } = await fetchRefreshToken(refreshToken);
|
|
|
|
if (!error) {
|
|
|
|
localStg.set('token', data.token);
|
|
|
|
localStg.set('refreshToken', data.refreshToken);
|
|
|
|
|
|
|
|
const config = { ...axiosConfig };
|
|
|
|
if (config.headers) {
|
|
|
|
config.headers.Authorization = data.token;
|
|
|
|
}
|
|
|
|
|
|
|
|
return config;
|
|
|
|
}
|
|
|
|
|
|
|
|
resetStore();
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
2024-05-08 11:57:58 +08:00
|
|
|
|
|
|
|
export function showErrorMsg(state: RequestInstanceState, message: string) {
|
|
|
|
if (!state.errMsgStack?.length) {
|
|
|
|
state.errMsgStack = [];
|
|
|
|
}
|
|
|
|
|
2024-06-26 17:30:11 +08:00
|
|
|
const isExist = state.errMsgStack.includes(message);
|
2024-05-08 11:57:58 +08:00
|
|
|
|
2024-06-26 17:30:11 +08:00
|
|
|
if (!isExist) {
|
|
|
|
state.errMsgStack.push(message);
|
2024-05-08 11:57:58 +08:00
|
|
|
|
2024-06-26 17:30:11 +08:00
|
|
|
window.$message?.error(message, {
|
|
|
|
onLeave: () => {
|
|
|
|
state.errMsgStack = state.errMsgStack.filter(msg => msg !== message);
|
|
|
|
|
|
|
|
setTimeout(() => {
|
|
|
|
state.errMsgStack = [];
|
|
|
|
}, 5000);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2024-05-08 11:57:58 +08:00
|
|
|
}
|