classy-pay-core
Version:
Shared tools used in ClassyPay-related projects
137 lines • 5.67 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIClient = exports.RequestResponseError = void 0;
// tslint:disable:max-classes-per-file
const oauth_1 = require("oauth");
const axios_1 = __importDefault(require("axios"));
const utils_1 = require("./utils/utils");
class RequestResponseError extends Error {
constructor(response, message) {
super(message);
this.response = response;
}
}
exports.RequestResponseError = RequestResponseError;
class APIClient {
constructor(clientId, clientSecret, oauthUrl, apiUrl, config = {}) {
if (!clientId)
throw Error('Cannot construct APIClient with null clientId');
if (!clientSecret)
throw Error('Cannot construct APIClient with null clientSecret');
if (!oauthUrl)
throw Error('Cannot construct APIClient with null oauthUrl');
if (!apiUrl)
throw Error('Cannot construct APIClient with null apiUrl');
this.clientId = clientId;
this.clientSecret = clientSecret;
this.oauthUrl = oauthUrl;
this.apiUrl = apiUrl;
this.timeout = config.timeout ? config.timeout : 120000;
this.log = config.log;
}
async getBearer(authParams = { grant_type: 'client_credentials' }) {
return await new Promise((resolve, reject) => {
const oauth2 = new oauth_1.OAuth2(this.clientId, this.clientSecret, this.oauthUrl, undefined, '/oauth2/auth');
oauth2.getOAuthAccessToken('', authParams, (err, accessToken) => {
if (err) {
reject(err);
}
else {
resolve(accessToken);
}
});
});
}
async makeRequest(bearer, method, resource, payload, useAPIUrl = true) {
const options = {
url: useAPIUrl ? (0, utils_1.normalizeUrl)(`${this.apiUrl}${resource}`) : resource,
timeout: this.timeout,
method,
headers: {
Authorization: `Bearer ${bearer}`,
'User-Agent': 'ClassyPay Node.JS',
},
};
if (payload) {
if (method !== 'POST' && method !== 'PUT') {
throw new Error('Not allowed to perform a GET or DELETE request with a payload');
}
options.headers = Object.assign(Object.assign({}, options.headers), { 'Content-Type': 'application/json' });
options.data = payload;
}
const response = await (0, utils_1.requestWithLogs)(options, this.log);
if (response.status < 200 || response.status > 299) {
throw new RequestResponseError(response, `API client received status code ${response.status}: ${response.data}`);
}
else {
return {
body: response.data ? (0, utils_1.JSONParseBig)(JSON.stringify(response.data)) : undefined,
nextPageUrl: response.headers.next_page_url,
};
}
}
async request(method, resource, payload, authParams, getAllPages = false) {
var _a;
if (getAllPages && method !== 'GET') {
throw new Error(`Can't pass getAllPages=true when using method type ${method}`);
}
const bearer = await this.getBearer(authParams);
if (getAllPages) {
let nextResource = (0, utils_1.normalizeUrl)(`${this.apiUrl}${resource}`);
let fullData;
while (nextResource) {
try {
const results = await this.makeRequest(bearer, method, nextResource, payload, false);
const data = results.body.data;
const nextPageUrl = results.nextPageUrl;
if (data) {
if (!fullData) {
fullData = data;
}
else {
fullData = fullData.concat(data);
}
}
if (nextPageUrl) {
nextResource = typeof nextPageUrl === 'string' ? nextPageUrl : nextPageUrl[0];
}
else {
nextResource = undefined;
}
}
catch (e) {
if (axios_1.default.isAxiosError(e) && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 404 && fullData) {
nextResource = undefined;
}
else {
throw e;
}
}
}
return fullData;
}
else {
return (await this.makeRequest(bearer, method, resource, payload)).body;
}
}
async get(resource, authparams) {
return await this.request('GET', resource, undefined, authparams);
}
async getAll(resource, authparams) {
return await this.request('GET', resource, undefined, authparams, true);
}
async post(resource, payload, authparams) {
return await this.request('POST', resource, payload, authparams);
}
async put(resource, payload, authparams) {
return await this.request('PUT', resource, payload, authparams);
}
async del(resource, authparams) {
return await this.request('DELETE', resource, undefined, authparams);
}
}
exports.APIClient = APIClient;
//# sourceMappingURL=APIClient.js.map