Added base classes to hadnle API Requests
This commit is contained in:
42
src/services/BaseAPI.tsx
Normal file
42
src/services/BaseAPI.tsx
Normal 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;
|
||||
10
src/services/CatalogAPI.tsx
Normal file
10
src/services/CatalogAPI.tsx
Normal 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); }
|
||||
Reference in New Issue
Block a user