Skip to content
Merged

Dev #264

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
14 changes: 14 additions & 0 deletions frontend/lib/api/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// frontend/lib/api/client.ts
import axios from 'axios';
import {setupInterceptors} from './interceptors'

const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});

// Prevent API calls during SSR
if (typeof window !== 'undefined') {
setupInterceptors(api);
}

export default api;
11 changes: 11 additions & 0 deletions frontend/lib/api/error-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// frontend/lib/api/error-handler.ts
import { ApiError } from './types';

export function handleApiError(error: any): ApiError {
const response = error.response || {};
return {
message: response.data?.message || 'Unexpected error occurred',
code: response.data?.code || 'UNKNOWN_ERROR',
status: response.status || 500,
};
}
33 changes: 33 additions & 0 deletions frontend/lib/api/interceptors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// frontend/lib/api/interceptors.ts
import type { AxiosInstance } from 'axios';
import { handleApiError } from './error-handler';

export function setupInterceptors(api: AxiosInstance) {
api.interceptors.request.use((config) => {
const token = localStorage.getItem('jwt');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});

api.interceptors.response.use(
(response) => response,
async (error) => {
const { status } = error.response || {};
if (status === 401) {
window.location.href = '/login';
}

// Retry logic: up to 3 attempts
const config = error.config;
if (!config.__retryCount) config.__retryCount = 0;
if (config.__retryCount < 3) {
config.__retryCount += 1;
return api(config);
}

return Promise.reject(handleApiError(error));
},
);
}
11 changes: 11 additions & 0 deletions frontend/lib/api/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// frontend/lib/api/types.ts
export interface ApiResponse<T> {
data: T;
status: number;
}

export interface ApiError {
message: string;
code: string;
status: number;
}