Skip to content

Commit

Permalink
feat: update authentication and error handling in ApiClient and query…
Browse files Browse the repository at this point in the history
…Client
  • Loading branch information
typeWolffo committed Nov 4, 2024
1 parent 34cc54b commit c0bc9f8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 23 deletions.
43 changes: 22 additions & 21 deletions apps/web/app/api/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,33 @@ export const ApiClient = new API({
withCredentials: true,
});

ApiClient.instance.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
ApiClient.instance.interceptors.request.use((config) => {
const isAuthEndpoint =
config.url?.includes("/login") ||
config.url?.includes("/refresh") ||
config.url?.includes("/register");

const isLoginRequest = originalRequest.url.includes("/login");
const isRefreshRequest = originalRequest.url.includes("/refresh");
if (!isAuthEndpoint && !useAuthStore.getState().isLoggedIn) {
const controller = new AbortController();
controller.abort();
config.signal = controller.signal;
}

if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
return config;
});

if (
!isLoginRequest &&
!isRefreshRequest &&
useAuthStore.getState().isLoggedIn
) {
try {
await ApiClient.api.authControllerRefreshTokens();
return ApiClient.instance(originalRequest);
} catch (refreshError) {
useAuthStore.getState().setLoggedIn(false);
return Promise.reject(refreshError);
}
ApiClient.instance.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401 && !error.config._retry) {
error.config._retry = true;
try {
await ApiClient.api.authControllerRefreshTokens();
return ApiClient.instance(error.config);
} catch {
useAuthStore.getState().setLoggedIn(false);
}
}

return Promise.reject(error);
}
);
19 changes: 17 additions & 2 deletions apps/web/app/api/queryClient.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
import { QueryClient } from "@tanstack/react-query";
import { isAxiosError } from "axios";
import { isAxiosError, isCancel } from "axios";

export const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry(failureCount, error) {
retry(failureCount, error: unknown) {
if (isCancel(error)) return false;

if (isAxiosError(error)) {
if (error.response?.status === 401) return false;
}

if (failureCount >= 3) return false;

return true;
},
},
mutations: {
retry(failureCount, error: unknown) {
if (isCancel(error)) return false;

if (isAxiosError(error)) {
if (error.response?.status === 401) return false;
}
Expand Down

0 comments on commit c0bc9f8

Please sign in to comment.