@sammachin/node-red-dragonpbx
Version:
A Node-RED node to append JSON objects to an array in msg.callScript
76 lines (65 loc) • 2.74 kB
JavaScript
var mustache = require('mustache');
mustache.escape = function(text) {return text;};
module.exports = function(RED) {
function BaseNode(config) {
RED.nodes.createNode(this, config);
const node = this;
// Store the configuration
this.jsonObject = config.jsonObject;
this.on('input', function(msg, send, done) {
const ctx=node.context();
// For backward compatibility with Node-RED 0.x
send = send || function() { node.send.apply(node, arguments); }
try {
// Get the data from global & flow context
const data = {
msg: msg,
flow : {},
global: {}
}
var keys = ctx.flow.keys();
for (var k in keys) {
data.flow[keys[k]] = ctx.flow.get(keys[k]);
}
var keys = ctx.global.keys();
for (var k in keys) {
data.global[keys[k]] = ctx.global.get(keys[k]);
}
//render the tempalte
const renderedObject = mustache.render(this.jsonObject, data)
// Parse the JSON object from the configuration
let objectToAppend;
try {
objectToAppend = (renderedObject) ? JSON.parse(renderedObject) : {};
} catch (e) {
node.error("Invalid JSON in configuration: " + e.message);
if (done) done(e);
return;
}
// Check if msg.callScript exists, if not, create it
if (!msg.callScript) {
msg.callScript = [];
}
// Check if msg.callScript is an array, if not make it an array
if (!Array.isArray(msg.callScript)) {
msg.callScript = [msg.callScript]; // Convert existing value to first element of array
}
// Append the JSON object to the array
msg.callScript.push(objectToAppend);
// Send the message
send(msg);
// Signal completion if callback is provided
if (done) {
done();
}
} catch (error) {
// Handle any unexpected errors
node.error(error, msg);
if (done) {
done(error);
}
}
});
}
RED.nodes.registerType("basenode", BaseNode);
}