@johntad/m-pesa
Version:
A TypeScript SDK for integrating M-Pesa mobile payment services into applications, enabling seamless money transfers and transactions.
80 lines (79 loc) • 3.44 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
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;
}
requestWithRetry(method, url, data, config) {
return __awaiter(this, void 0, void 0, function* () {
let attempts = 0;
while (attempts < this.retries) {
try {
attempts++;
switch (method) {
case 'GET':
return yield this.axiosInstance.get(url, config);
case 'POST':
return yield this.axiosInstance.post(url, data, config);
case 'PUT':
return yield this.axiosInstance.put(url, data, config);
case 'DELETE':
return yield 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
});
}
fetchPaginated(url_1, config_1) {
return __awaiter(this, arguments, void 0, function* (url, config, paginationKey = 'next', resultsKey = 'data') {
const results = [];
let nextPage = url;
while (nextPage) {
const response = yield 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;