@apidaze/node-red-contrib-apidaze
Version:
Node-RED module for Apidaze
109 lines (92 loc) • 3.2 kB
JavaScript
module.exports = function (RED) {
'use strict';
const jsonata = require('jsonata');
const { HttpsProxyAgent } = require('hpagent');
const evaluate = (payload, data) => {
return Object
.entries(payload)
.reduce((result, [key, value]) => {
try {
return {
...result,
[key]: jsonata(value).evaluate(data),
};
} catch (err) {
return {
...result,
[key]: value
};
}
}, {});
}
function ApiRequest(config) {
RED.nodes.createNode(this, config);
this.accountNode = RED.nodes.getNode(config.account);
this.path = config.path;
this.operation = config.operation;
this.data = config.data;
this.continue = config.continue; // true or false
this.proxy = config.proxy; // may be empty string for disabling
this.timeout = config.timeout; // may be null for no timeout
if (!this.accountNode) {
this.warn('Missing account node in the API request!');
}
if (Object.values(this.data).length === 0) {
this.warn('Missing data for the operation!');
}
const requestOptions = {};
if (this.proxy) {
const agent = new HttpsProxyAgent({
keepAlive: true,
keepAliveMsecs: 1000,
maxSockets: 256,
maxFreeSockets: 256,
proxy: this.proxy
});
requestOptions.agent = {
https: agent
};
}
if (this.timeout) {
requestOptions.timeout = this.timeout;
}
this.on('input', async (msg, send, done) => {
let operationFunc = () => {};
if (this.operation === 'sms') {
const { to, from, message } = evaluate(this.data, msg);
operationFunc = () => this.accountNode.client.messages.send(from, to, message, requestOptions);
} else if (this.operation === 'transfer') {
const { callUuid } = evaluate(this.data);
operationFunc = () => this.accountNode.client.calls.transfer(callUuid, requestOptions);
} else if (this.operation === 'eavesdrop') {
const { callUuid, interceptorUuid } = evaluate(this.data);
const payload = { interceptorUuid, liveMonitor: true };
operationFunc = () => this.accountNode.client.calls.intercept(callUuid, payload, requestOptions);
} else if (this.operation === 'intercept') {
const { callUuid, interceptorUuid } = evaluate(this.data);
const payload = { interceptorUuid };
operationFunc = () => this.accountNode.client.calls.intercept(callUuid, payload, requestOptions);
}
if (this.continue) {
try {
operationFunc();
} catch (err) {
this.warn(err);
}
} else {
try {
const { body } = await operationFunc();
// const body = await operationFunc();
// stack responses after each other as there may be multiple requests
const existingResponses = msg.responses || [];
msg.responses = existingResponses.concat(body);
} catch (err) {
this.error(err);
}
}
send(msg);
done();
});
}
RED.nodes.registerType('api-request', ApiRequest);
};