Skip to content

Commit

Permalink
optimize(projects): optimize response code comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
honghuangdc committed Sep 8, 2024
1 parent 6bb66a0 commit d702524
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/service/request/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const request = createFlatRequest<App.Service.Response, RequestInstanceSt
},
async onBackendFail(response, instance) {
const authStore = useAuthStore();
const responseCode = String(response.data.code);

function handleLogout() {
authStore.resetStore();
Expand All @@ -49,14 +50,14 @@ export const request = createFlatRequest<App.Service.Response, RequestInstanceSt

// when the backend response code is in `logoutCodes`, it means the user will be logged out and redirected to login page
const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
if (logoutCodes.includes(response.data.code)) {
if (logoutCodes.includes(responseCode)) {
handleLogout();
return null;
}

// when the backend response code is in `modalLogoutCodes`, it means the user will be logged out by displaying a modal
const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
if (modalLogoutCodes.includes(response.data.code) && !request.state.errMsgStack?.includes(response.data.msg)) {
if (modalLogoutCodes.includes(responseCode) && !request.state.errMsgStack?.includes(responseCode)) {
request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.msg];

// prevent the user from refreshing the page
Expand All @@ -81,7 +82,7 @@ export const request = createFlatRequest<App.Service.Response, RequestInstanceSt
// when the backend response code is in `expiredTokenCodes`, it means the token is expired, and refresh token
// the api `refreshToken` can not return error code in `expiredTokenCodes`, otherwise it will be a dead loop, should return `logoutCodes` or `modalLogoutCodes`
const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
if (expiredTokenCodes.includes(response.data.code) && !request.state.isRefreshingToken) {
if (expiredTokenCodes.includes(responseCode) && !request.state.isRefreshingToken) {
request.state.isRefreshingToken = true;

const refreshConfig = await handleRefreshToken(response.config);
Expand All @@ -107,7 +108,7 @@ export const request = createFlatRequest<App.Service.Response, RequestInstanceSt
// get backend error message and code
if (error.code === BACKEND_ERROR_CODE) {
message = error.response?.data?.msg || message;
backendErrorCode = error.response?.data?.code || '';
backendErrorCode = String(error.response?.data?.code) || '';
}

// the error message is displayed in the modal
Expand Down

0 comments on commit d702524

Please sign in to comment.