/
node-set-credentials.js
46 lines (39 loc) · 1.49 KB
/
node-set-credentials.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// --------------------------------------------------------------------------
// NODE-RED
// --------------------------------------------------------------------------
module.exports = function(RED) {
const register = function(config) {
RED.nodes.createNode(this, config);
let node = this;
config.rules = RED.nodes.getNode(config.rules);
this.on('input', (data) => { input(RED, node, data, config) });
}
RED.nodes.registerType("set-credentials", register, {});
}
const input = (RED, node, data, config) => {
var creds = (config.rules.credentials.rules_to) ? JSON.parse(config.rules.credentials.rules_to) : [''];
var rules = config.rules.rules;
var obj = {}
for (let i=0; i<rules.length; i++) {
if (!rules[i].p) continue;
obj[rules[i].p] = getValue(creds[i], rules[i].tot);
}
if (config.setType === "global") node.context().global.set(config.set, obj);
else RED.util.setMessageProperty(data, config.set, obj);
return node.send(data);
}
function getValue(val, typ) {
switch(typ) {
case "str":
if (typeof(val) === "string") return val;
else if (typeof(val === "object")) return JSON.stringify(val);
else return String(val);
case "num":
return Number(val);
case "json":
if (typeof(val) === "object") return val;
else if (typeof(val) === "string") return JSON.parse(val);
default :
return val;
}
}