Added base classes to hadnle API Requests

This commit is contained in:
2025-10-24 19:48:48 +02:00
parent de1cca5739
commit 4937aa3980
2 changed files with 52 additions and 0 deletions

42
src/services/BaseAPI.tsx Normal file
View File

@@ -0,0 +1,42 @@
import axios, { AxiosInstance } from "axios";
class BaseAPI {
private api: AxiosInstance;
constructor(url: string) {
this.api = axios.create({
baseURL: url,
headers: {
'Content-Type': 'application/json',
}
});
this.api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
this.api.interceptors.response.use(
(response) => response,
(error) => {
if (error.respone.status === 401) {
alert('Unauthorized'); // FIXME
}
return Promise.reject(error);
}
)
}
getAPI(): AxiosInstance {
return this.api;
}
}
export default BaseAPI;

View File

@@ -0,0 +1,10 @@
import BaseAPI from "./BaseAPI";
// const baseUrl = 'https://egommerce.io:31800'; // Gateway
const baseUrl = process.env.REACT_APP_API_CATALOG_URL ?? 'https://SOME_FAILSAFE_API_URL';
const base = new BaseAPI(baseUrl); // FIXME is it the rigth way?
export const GetProducts = async() => { return base.getAPI().get('/product'); }
export const GetProduct = async(id: string) => { return base.getAPI().get('/product/'+ id); }