import { getTokenFromLocalStorage } from "@config/token"; import { ApiError } from "@models/Server.Error.model"; import axios from "@config/axios.config"; class ApiService { private normalizeError(error: unknown): ApiError { if (error && typeof error === "object" && "response" in error) { const response = (error as { response?: { data?: any; status?: number } }).response; const data = response?.data; if (data) { const msg = data.desc || data.message || JSON.stringify(data.details || data) || "No pudimos completar la operación."; return new ApiError(data.code || response?.status || 500, msg); } return new ApiError(response?.status || 500, "No pudimos comunicarnos con el servidor."); } if (error instanceof Error) { return new ApiError(500, error.message); } return new ApiError(500, "No pudimos comunicarnos con el servidor."); } /** * Sends a HTTP POST request to the specified endpoint with the provided data * and returns a promise that resolves to the response data. * * @param {string} endpoint - The URL or path of the API endpoint to send the request to. * @param {object} data - The data to be sent with the request. * @return {Promise} A promise that resolves to the response data of type T. */ post(endpoint: string, data: object): Promise { return new Promise((resolve, reject) => { axios() .post(endpoint, data) .then((response) => { resolve(response.data); }) .catch((error) => { reject(this.normalizeError(error)); }); }); } postFile(endpoint: string, data: FormData): Promise { return new Promise((resolve, reject) => { axios() .post(endpoint, data, { headers: { "content-type": "multipart/form-data", Authorization: getTokenFromLocalStorage(), }, }) .then((response) => { resolve(response.data); }) .catch((error) => { reject(this.normalizeError(error)); }); }); } } const API = new ApiService(); export default API;