Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/services/api/axiosClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import axios from "axios";
import { API_CONFIG } from "./config";
import { userService } from "./userService";

// Create axios instance with default configuration
const axiosClient = axios.create({
Expand Down Expand Up @@ -35,6 +36,42 @@ axiosClient.interceptors.response.use(
return response;
},
async (error) => {
const originalRequest = error.config;

if (
error.response &&
error.response.status === 401 &&
!originalRequest._retry
) {
originalRequest._retry = true;
try {
let refreshToken = null;
if (typeof window !== "undefined") {
const authTokens = localStorage.getItem("auth_tokens");
if (authTokens) {
const tokens = JSON.parse(authTokens);
refreshToken = tokens.refreshToken;
}
}
const data = await userService.refreshAccessToken(refreshToken);
if (typeof window !== "undefined") {
localStorage.setItem("auth_tokens", JSON.stringify(data.tokens));
}

originalRequest.headers[
"Authorization"
] = `Bearer ${data.tokens.accessToken}`;
return axiosClient(originalRequest);
} catch (refreshError) {
if (typeof window !== "undefined") {
localStorage.removeItem("auth_tokens");
localStorage.removeItem("auth_user");
window.location.href = "/login";
}

return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
Expand Down
1 change: 1 addition & 0 deletions src/services/api/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const API_ENDPOINTS = {
// Auth endpoints
AUTH: {
CREATE: "/auth/create-login",
REFRESH: "/auth/refresh-token",
},

// User endpoints
Expand Down
12 changes: 12 additions & 0 deletions src/services/api/userService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ interface UpdateUserParams {
picture?: string;
}

interface RefreshTokenParams {
refreshToken: string;
}

interface User {
id: string;
username: string;
Expand All @@ -39,6 +43,13 @@ const createUser = async (params: CreateUserParams): Promise<AuthResponse> => {
return response.data;
};

const refreshAccessToken = async (
params: RefreshTokenParams
): Promise<AuthResponse> => {
const response = await axiosClient.post(API_ENDPOINTS.AUTH.REFRESH);
return response.data;
};

const updateUser = async (params: UpdateUserParams): Promise<User> => {
const response = await axiosClient.patch(API_ENDPOINTS.USERS.UPDATE, params);
return response.data;
Expand All @@ -53,4 +64,5 @@ export const userService = {
createUser,
updateUser,
getUserById,
refreshAccessToken,
};