65 lines
2.6 KiB
TypeScript
65 lines
2.6 KiB
TypeScript
import { getTokenFromLocalStorage } from "@config/token";
|
|
import { ApiError } from "@models/Server.Error.model";
|
|
import axios from "@config/axios.config";
|
|
|
|
class ApiService {
|
|
/**
|
|
* 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) => {
|
|
try {
|
|
const data = error.response.data;
|
|
const msg = data.desc || data.message || JSON.stringify(data.details || data);
|
|
reject(new ApiError(data.code || error.response.status || 500, msg));
|
|
} catch {
|
|
const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
|
|
reject(new ApiError(500, errorMessage));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
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) => {
|
|
try {
|
|
console.error("Full API Error:", error.response?.data);
|
|
const data = error.response.data;
|
|
const msg = data.desc || data.message || JSON.stringify(data.details || data);
|
|
reject(new ApiError(data.code || error.response.status || 500, msg));
|
|
} catch (e) {
|
|
console.error(e);
|
|
const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
|
|
reject(new ApiError(500, errorMessage));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
const API = new ApiService();
|
|
|
|
export default API;
|