kawkab-frontend
Version:
Kawkab frontend is a frontend library for the Kawkab framework
61 lines (60 loc) • 2.07 kB
JavaScript
import axios from 'axios';
export class ApiError extends Error {
status;
data;
constructor(message, status, data) {
super(message);
this.name = 'ApiError';
this.status = status;
this.data = data;
}
}
export class ApiClient {
axiosInstance;
constructor(config) {
this.axiosInstance = axios.create({
baseURL: config.baseURL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
this.axiosInstance.interceptors.request.use((axiosConfig) => {
const token = config.getToken();
if (token) {
axiosConfig.headers.Authorization = `Bearer ${token}`;
}
return axiosConfig;
}, (error) => {
return Promise.reject(error);
});
this.axiosInstance.interceptors.response.use((response) => response, (error) => {
if (axios.isAxiosError(error) && error.response) {
const { status, data } = error.response;
const message = data?.message || error.message;
return Promise.reject(new ApiError(message, status, data));
}
else {
return Promise.reject(new ApiError(error.message));
}
});
}
handleResponse(promise) {
return promise.then(response => response.data);
}
get(endpoint, config) {
return this.handleResponse(this.axiosInstance.get(endpoint, config));
}
post(endpoint, body, config) {
return this.handleResponse(this.axiosInstance.post(endpoint, body, config));
}
put(endpoint, body, config) {
return this.handleResponse(this.axiosInstance.put(endpoint, body, config));
}
patch(endpoint, body, config) {
return this.handleResponse(this.axiosInstance.patch(endpoint, body, config));
}
delete(endpoint, config) {
return this.handleResponse(this.axiosInstance.delete(endpoint, config));
}
}