forked from s1r-J/node-red-contrib-loop-processing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
array-loop.js
97 lines (86 loc) · 2.96 KB
/
array-loop.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
module.exports = function (RED) {
'use strict';
function setProperty(node, msg, name, type, value) {
if (type === 'msg') {
msg[name] = value;
} else if (type === 'flow') {
node.context().flow.set(name, value);
} else if (type === 'global') {
node.context().global.set(name, value);
}
}
function sendErrorMessage(node, text) {
node.status({
fill: 'red',
shape: 'ring',
text: text
});
node.error(text, msg);
}
function ArrayLoopNode(n) {
RED.nodes.createNode(this, n);
var node = this;
node.key = n.key;
node.keyType = n.keyType;
node.array = n.array;
node.arrayType = n.arrayType;
node.reset = n.reset;
node.resetValue = n.resetValue;
this.on('input', function (msg) {
let key = RED.util.evaluateNodeProperty(node.key, node.keyType, node, msg);
let array = RED.util.evaluateNodeProperty(node.array, node.arrayType, node, msg);
if (!Array.isArray(array)) {
let text = RED._('array-loop.errors.arraynotarray') + array;
sendErrorMessage(node, text);
}
if (key === void 0 || key === null || key === '') {
// initialize
key = 0;
} else {
key += 1;
}
setProperty(node, msg, node.key, node.keyType, key);
setProperty(node, msg, node.array, node.arrayType, array);
let isLoop = array.length > key;
if (isLoop) {
// run in loop
node.status({
fill: 'blue',
shape: 'dot',
text: 'loop'
});
msg.payload = array[key];
node.send([null, msg]);
} else {
// exit loop
if (node.reset) {
let resetValue = null;
switch (node.resetValue) {
case 'value-null':
resetValue = null;
break;
case 'value-undefined':
resetValue = undefined;
break;
case 'value-empty':
resetValue = '';
break;
default:
// not come here
}
setProperty(node, msg, node.key, node.keyType, resetValue);
}
node.status({
fill: 'grey',
shape: 'ring',
text: 'exit loop'
});
node.send(msg);
}
});
this.on('close', function () {
node.status({});
});
}
RED.nodes.registerType('array-loop', ArrayLoopNode);
}