UNPKG

@andranik-arakelyan/js-utilities

Version:
1 lines 1.34 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseApiClient=void 0;const axios_1=require("axios");class BaseApiClient{config;axiosInstance;customHeaders={};constructor(config){this.config=config;this.axiosInstance=axios_1.default.create({baseURL:`${config.baseUrl}${config.urlPrefix||""}`});this.customHeaders={"Content-Type":"application/json"}}setHeaders(headers){for(const[key,value]of Object.entries(headers)){if(value===null){delete this.customHeaders[key]}else{this.customHeaders[key]=value}}}getHeaders(){return{...this.customHeaders}}async request(options){const{path:path,query:query,body:body,method:method="GET"}=options;try{const response=await this.axiosInstance.request({url:path,method:method,params:query,data:body,headers:this.customHeaders});return this.handleResponse(response)}catch(error){if(axios_1.default.isAxiosError(error)&&error.response){return this.handleResponse(error.response)}throw error}}handleResponse(response){const data=response.data;if(response.status<200||response.status>=300){const errorMessage=data?.error||data?.message||response.statusText;const error=new Error(errorMessage);error.response=data;throw error}if(data?.success===false){const error=new Error(data.error||"Request failed");error.response=data;throw error}return data}}exports.BaseApiClient=BaseApiClient;