refactor: modularize API client by splitting resources into individual files and standardizing HTTP request handling.

This commit is contained in:
Jose Selesan
2026-04-20 16:05:37 -03:00
parent 28fd51f926
commit 34cb63364c
11 changed files with 327 additions and 267 deletions

View File

@@ -0,0 +1,60 @@
import axios, { AxiosError, type AxiosInstance } from 'axios';
import { ApiClientError, apiBaseUrl, handlers } from './base';
export const http: AxiosInstance = axios.create({
baseURL: apiBaseUrl,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
function extractMessage(details: unknown, fallback: string): string {
if (
typeof details === 'object' &&
details &&
'message' in details &&
typeof details.message === 'string'
) {
return details.message;
}
return fallback;
}
function normalizeError(error: unknown): ApiClientError {
if (error instanceof ApiClientError) return error;
if (axios.isAxiosError(error)) {
const status = error.response?.status;
const details = error.response?.data;
return new ApiClientError(extractMessage(details, error.message || 'Request failed'), {
status,
details,
causeError: error,
});
}
if (error instanceof Error) {
return new ApiClientError(error.message, { causeError: error });
}
return new ApiClientError('Error inesperado.', { causeError: error });
}
http.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const normalized = normalizeError(error);
if (normalized.status === 403 && handlers.onForbidden) {
await handlers.onForbidden(normalized);
}
if (handlers.onError) {
await handlers.onError(normalized);
}
return Promise.reject(normalized);
}
);