afrimomo-sdk
Version:
A unified SDK for African payment providers
148 lines • 5.56 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = void 0;
const axios_1 = __importDefault(require("axios"));
const logger_1 = require("./logger");
class HttpClient {
requestHook;
axiosInstance;
serviceName;
authStrategy;
constructor(config, authStrategy = { type: "none" }, requestHook) {
this.requestHook = requestHook;
this.serviceName = config.serviceName;
this.authStrategy = authStrategy;
const headers = {
"Content-Type": "application/json",
Accept: "application/json",
...config.defaultHeaders,
};
if (authStrategy.type === "bearer" && authStrategy.token) {
headers.Authorization = `Bearer ${authStrategy.token}`;
}
else if (authStrategy.type === "basic" &&
authStrategy.username &&
authStrategy.password) {
const basicAuth = Buffer.from(`${authStrategy.username}:${authStrategy.password}`).toString("base64");
headers.Authorization = `Basic ${basicAuth}`;
}
this.axiosInstance = axios_1.default.create({
baseURL: config.baseUrl,
headers,
timeout: config.timeoutMs ?? 30000,
});
this.setupInterceptors();
}
setupInterceptors() {
this.axiosInstance.interceptors.request.use(async (config) => {
if (this.authStrategy.type === "custom" &&
this.authStrategy.getAuthHeader) {
const authHeader = await this.authStrategy.getAuthHeader();
config.headers.Authorization = authHeader;
}
if (this.requestHook?.onRequest) {
config = await this.requestHook.onRequest(config);
}
logger_1.logger.debug(`${this.serviceName} API Request:`, {
method: config.method,
url: config.url,
params: config.params,
});
return config;
}, async (error) => {
logger_1.logger.error(`${this.serviceName} API Request Error:`, error);
if (this.requestHook?.onRequestError) {
return this.requestHook.onRequestError(error);
}
return Promise.reject(error);
});
this.axiosInstance.interceptors.response.use((response) => {
logger_1.logger.debug(`${this.serviceName} API Response:`, {
status: response.status,
statusText: response.statusText,
data: response.data,
});
return response;
}, (error) => {
logger_1.logger.error(`${this.serviceName} API Response Error:`, {
message: error.message,
response: error.response?.data,
});
return Promise.reject(error);
});
}
handleApiError(error, context) {
logger_1.logger.error(`${this.serviceName} API Error - ${context}:`, error);
let errorMessage = `An error occurred during ${context}`;
let statusCode = 500;
let errorObject = "{}";
if (axios_1.default.isAxiosError(error) && error.response) {
statusCode = error.response.status;
try {
const data = error.response.data;
errorMessage = data.message || data.error || errorMessage;
errorObject = JSON.stringify(data);
}
catch {
errorMessage = `Failed to parse error response during ${context}`;
}
}
else if (error instanceof Error) {
errorMessage = error.message;
}
return { errorMessage, statusCode, errorObject };
}
async get(endpoint, context = "GET request", config = {}) {
try {
const response = await this.axiosInstance.get(endpoint, config);
return response.data;
}
catch (error) {
throw this.handleApiError(error, context);
}
}
async post(endpoint, data, context = "POST request", config = {}) {
try {
const response = await this.axiosInstance.post(endpoint, data, config);
return response.data;
}
catch (error) {
throw this.handleApiError(error, context);
}
}
async put(endpoint, data, context = "PUT request", config = {}) {
try {
const response = await this.axiosInstance.put(endpoint, data, config);
return response.data;
}
catch (error) {
throw this.handleApiError(error, context);
}
}
async patch(endpoint, data, context = "PATCH request", config = {}) {
try {
const response = await this.axiosInstance.patch(endpoint, data, config);
return response.data;
}
catch (error) {
throw this.handleApiError(error, context);
}
}
async delete(endpoint, context = "DELETE request", config = {}) {
try {
const response = await this.axiosInstance.delete(endpoint, config);
return response.data;
}
catch (error) {
throw this.handleApiError(error, context);
}
}
getInstance() {
return this.axiosInstance;
}
}
exports.HttpClient = HttpClient;
//# sourceMappingURL=httpClient.js.map