chargebee
Version:
A library for integrating with Chargebee.
96 lines (95 loc) • 4.07 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestWrapper = void 0;
const util_js_1 = require("./util.js");
const coreCommon_js_1 = require("./coreCommon.js");
const node_buffer_1 = require("node:buffer");
class RequestWrapper {
constructor(args, apiCall, envArg) {
this.getRequest = () => {
return this.request();
};
this.args = args;
this.apiCall = apiCall;
this.envArg = envArg;
this.httpHeaders = {};
if (this.apiCall.hasIdInUrl) {
RequestWrapper._validateIdParam(this.args[0]);
}
}
static _validateIdParam(idParam) {
if (!idParam || typeof idParam !== 'string' || idParam.trim().length < 1) {
throw new Error('the required id parameter missing or wrong');
}
return idParam;
}
request() {
let env = {};
(0, util_js_1.extend)(true, env, this.envArg);
const urlIdParam = this.apiCall.hasIdInUrl ? this.args[0] : null;
let params = this.apiCall.hasIdInUrl
? this.args[1]
: this.args[0];
let headers = this.apiCall.hasIdInUrl ? this.args[2] : this.args[1];
Object.assign(this.httpHeaders, headers);
const promise = new Promise(async (resolve, reject) => {
function callBackWrapper(err, response) {
if (err) {
reject(err);
}
else {
resolve(response);
}
}
try {
let path = (0, util_js_1.getApiURL)(env, this.apiCall.urlPrefix, this.apiCall.urlSuffix, urlIdParam);
if (typeof params === 'undefined' || params === null) {
params = {};
}
if (this.apiCall.httpMethod === 'GET') {
params = (0, util_js_1.serialize)(params);
let queryParam = this.apiCall.isListReq
? (0, util_js_1.encodeListParams)(params)
: (0, util_js_1.encodeParams)(params);
path += '?' + queryParam;
params = {};
}
const jsonKeys = this.apiCall.jsonKeys;
let data = this.apiCall.isJsonRequest
? JSON.stringify(params)
: (0, util_js_1.encodeParams)(params, undefined, undefined, undefined, jsonKeys);
if (data.length) {
(0, util_js_1.extend)(true, this.httpHeaders, {
'Content-Length': data.length,
});
}
const contentType = this.apiCall.isJsonRequest
? 'application/json;charset=UTF-8'
: 'application/x-www-form-urlencoded; charset=utf-8';
(0, util_js_1.extend)(true, this.httpHeaders, {
Authorization: 'Basic ' + node_buffer_1.Buffer.from(env.apiKey + ':').toString('base64'),
Accept: 'application/json',
'Content-Type': contentType,
'User-Agent': 'Chargebee-NodeJs-Client ' + env.clientVersion,
'Lang-Version': typeof process === 'undefined' ? '' : process.version,
});
const resp = await this.envArg.httpClient.makeApiRequest({
host: (0, util_js_1.getHost)(env, this.apiCall.subDomain),
port: env.port,
path,
method: this.apiCall.httpMethod,
protocol: env.protocol,
headers: this.httpHeaders,
data: data,
timeout: env.timeout,
});
(0, coreCommon_js_1.handleResponse)(callBackWrapper, resp);
}
catch (err) {
callBackWrapper(err, null);
}
});
return (0, util_js_1.callbackifyPromise)(promise);
}
}
exports.RequestWrapper = RequestWrapper;