69 lines
2.4 KiB
TypeScript
69 lines
2.4 KiB
TypeScript
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<T>} A promise that resolves to the response data of type T.
|
|
*/
|
|
post<T>(endpoint: string, data: object): Promise<T> {
|
|
return new Promise<T>((resolve, reject) => {
|
|
axios()
|
|
.post<T>(endpoint, data)
|
|
.then((response) => {
|
|
resolve(response.data);
|
|
})
|
|
.catch((error) => {
|
|
reject(this.normalizeError(error));
|
|
});
|
|
});
|
|
}
|
|
|
|
postFile<T>(endpoint: string, data: FormData): Promise<T> {
|
|
return new Promise<T>((resolve, reject) => {
|
|
axios()
|
|
.post<T>(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;
|