mirror of
https://github.com/soybeanjs/soybean-admin.git
synced 2025-10-13 05:13:41 +08:00
feat(projects): add request refresh token & logout
This commit is contained in:
@@ -1,11 +1,19 @@
|
||||
import type { AxiosResponse } from 'axios';
|
||||
import { BACKEND_ERROR_CODE, createFlatRequest, createRequest } from '@sa/axios';
|
||||
import { useAuthStore } from '@/store/modules/auth';
|
||||
import { localStg } from '@/utils/storage';
|
||||
import { getServiceBaseURL } from '@/utils/service';
|
||||
import { handleRefreshToken } from './shared';
|
||||
|
||||
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
|
||||
const { baseURL, otherBaseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);
|
||||
|
||||
export const request = createFlatRequest<App.Service.Response>(
|
||||
interface InstanceState {
|
||||
/** whether the request is refreshing token */
|
||||
isRefreshingToken: boolean;
|
||||
}
|
||||
|
||||
export const request = createFlatRequest<App.Service.Response, InstanceState>(
|
||||
{
|
||||
baseURL,
|
||||
headers: {
|
||||
@@ -28,9 +36,36 @@ export const request = createFlatRequest<App.Service.Response>(
|
||||
// you can change this logic by yourself
|
||||
return response.data.code === '0000';
|
||||
},
|
||||
async onBackendFail(_response) {
|
||||
async onBackendFail(response, instance) {
|
||||
// when the backend response code is not "0000", it means the request is fail
|
||||
// for example: the token is expired, refresh token and retry request
|
||||
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// when the backend response code is "8888", it means logout the system and redirect to login page
|
||||
// the following code is an example, you can change it by yourself
|
||||
const logoutCodes: (string | number)[] = ['8888'];
|
||||
if (logoutCodes.includes(response.data.code)) {
|
||||
authStore.resetStore();
|
||||
return null;
|
||||
}
|
||||
|
||||
// when the backend response code is "9999", it means the token is expired, and refresh token
|
||||
// the api `refreshToken` can not return the code "9999", otherwise it will be a dead loop, can return `logoutCodes`
|
||||
const refreshTokenCodes: (string | number)[] = ['9999'];
|
||||
if (refreshTokenCodes.includes(response.data.code) && !request.state.isRefreshingToken) {
|
||||
request.state.isRefreshingToken = true;
|
||||
|
||||
const refreshConfig = await handleRefreshToken(response.config);
|
||||
|
||||
request.state.isRefreshingToken = false;
|
||||
|
||||
if (refreshConfig) {
|
||||
return instance.request(refreshConfig) as Promise<AxiosResponse>;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
transformBackendResponse(response) {
|
||||
return response.data.data;
|
||||
|
Reference in New Issue
Block a user