customerio-node
Version:
A node client for the Customer.io event API. http://customer.io
98 lines (97 loc) • 3.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const https_1 = require("https");
const url_1 = require("url");
const utils_1 = require("./utils");
const version_1 = require("./version");
const TIMEOUT = 10000;
class CIORequest {
constructor(auth, defaults) {
if (typeof auth === 'object') {
this.apikey = auth.apikey;
this.siteid = auth.siteid;
this.auth = `Basic ${Buffer.from(`${this.siteid}:${this.apikey}`, 'utf8').toString('base64')}`;
}
else {
this.appKey = auth;
this.auth = `Bearer ${this.appKey}`;
}
this.defaults = Object.assign({
timeout: TIMEOUT,
}, defaults);
}
options(uri, method, data) {
const body = data ? JSON.stringify(data) : null;
const headers = {
Authorization: this.auth,
'Content-Type': 'application/json',
'Content-Length': body ? Buffer.byteLength(body, 'utf8') : 0,
'User-Agent': `Customer.io Node Client/${version_1.version}`,
};
return { method, uri, headers, body };
}
handler({ uri, body, method, headers }) {
return new Promise((resolve, reject) => {
let url = new url_1.URL(uri);
let options = Object.assign({}, this.defaults, {
method,
headers,
hostname: url.hostname,
path: `${url.pathname}${url.search}`,
});
let req = (0, https_1.request)(options, (res) => {
let chunks = [];
res.on('data', (data) => {
chunks.push(data);
});
res.on('end', () => {
var _a;
let body = Buffer.concat(chunks).toString('utf-8');
let json = {};
if ([301, 302, 307, 308].includes((_a = res.statusCode) !== null && _a !== void 0 ? _a : 0)) {
let newURI = res.headers.location;
if (newURI == null) {
return reject(new Error(`Received a ${res.statusCode} status, but no Location header was present`));
}
return this.handler({ uri: newURI, body, method, headers }).then(resolve).catch(reject);
}
try {
if (body && body.length) {
json = JSON.parse(body);
}
}
catch (error) {
const message = `Unable to parse JSON. Error: ${error} \nBody:\n ${body}`;
return reject(new Error(message));
}
if (res.statusCode == 200 || res.statusCode == 201) {
resolve(json);
}
else {
reject(new utils_1.CustomerIORequestError(json, res.statusCode || 0, res, body));
}
});
});
req.on('error', (error) => {
reject(error);
});
if (body) {
req.write(body);
}
req.end();
});
}
get(uri) {
return this.handler(this.options(uri, 'GET'));
}
put(uri, data = {}) {
return this.handler(this.options(uri, 'PUT', data));
}
destroy(uri) {
return this.handler(this.options(uri, 'DELETE'));
}
post(uri, data = {}) {
return this.handler(this.options(uri, 'POST', data));
}
}
exports.default = CIORequest;