UNPKG

@safaricom-et/mpesa-node-js-sdk

Version:

A TypeScript SDK for integrating M-Pesa mobile payment services into applications, enabling seamless money transfers and transactions.

67 lines (66 loc) 2.46 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.APIClient = void 0; const axios_1 = __importDefault(require("axios")); class APIClient { constructor(config) { this.axiosInstance = axios_1.default.create({ baseURL: config.baseURL, timeout: config.timeout || 5000, }); this.retries = config.retries || 3; } async requestWithRetry(method, url, data, config) { let attempts = 0; while (attempts < this.retries) { try { attempts++; switch (method) { case 'GET': return await this.axiosInstance.get(url, config); case 'POST': return await this.axiosInstance.post(url, data, config); case 'PUT': return await this.axiosInstance.put(url, data, config); case 'DELETE': return await this.axiosInstance.delete(url, config); default: throw new Error(`Unsupported HTTP method: ${method}`); } } catch (error) { if (attempts >= this.retries) { this.handleError(error); // Throw the error after max retries } } } throw new Error('Request failed after max retries.'); // Fallback, though retries handle this } async fetchPaginated(url, config, paginationKey = 'next', resultsKey = 'data') { const results = []; let nextPage = url; while (nextPage) { const response = await this.requestWithRetry(`GET`, nextPage, undefined, config); const responseData = response.data; // Collect results if (Array.isArray(responseData[resultsKey])) { results.push(...responseData[resultsKey]); } // Determine the next page nextPage = responseData[paginationKey] || null; } return results; } handleError(error) { if (error.response) { throw error; } else { throw new Error(`Error: ${error.message}`); } } } exports.APIClient = APIClient;