72 lines
2.4 KiB
JavaScript
72 lines
2.4 KiB
JavaScript
|
|
module.exports = function (RED) {
|
|
"use strict";
|
|
|
|
function ParserEntryPoint(n) {
|
|
RED.nodes.createNode(this, n);
|
|
this.property = n.property;
|
|
this.help_text = n.help_text;
|
|
this.on("input", msg => {
|
|
RED.util.evaluateNodeProperty(this.property, "msg", this, msg,
|
|
(err, value) => {
|
|
if (err) {
|
|
this.error(`Can't evaluate msg.${this.property}`);
|
|
} else {
|
|
let tokens = value.trim().toLowerCase().split(" ");
|
|
msg.token_parser = {
|
|
new_tokens: tokens,
|
|
consumed_tokens: [],
|
|
help_message: this.help_text,
|
|
on_error: (maybe_error) => {
|
|
let err = maybe_error ? maybe_error : this.help_text;
|
|
this.send([undefined, err]);
|
|
}
|
|
};
|
|
this.send([msg, undefined]);
|
|
};
|
|
});
|
|
});
|
|
}
|
|
|
|
RED.nodes.registerType("parser-entry-point", ParserEntryPoint);
|
|
|
|
function ConsumaToken(n) {
|
|
RED.nodes.createNode(this, n);
|
|
this.rules = n.rules;
|
|
this.behavior= n.behavior;
|
|
this.checkall= n.checkall;
|
|
function check_rule(r, token) {
|
|
switch(r.t){
|
|
case "eq":
|
|
return token == r.v.toLowerCase();
|
|
case "regex":
|
|
let reg = new RegExp(r.v);
|
|
return token.match(reg);
|
|
}
|
|
}
|
|
this.on("input", msg => {
|
|
let token = msg.token_parser.new_tokens.shift() || "";
|
|
msg.token_parser.consumed_tokens.push(token);
|
|
let out = [];
|
|
let n_matches = 0;
|
|
for (let r of this.rules) {
|
|
if(check_rule(r, token)){
|
|
out.push(msg);
|
|
n_matches += 1;
|
|
if (!this.checkall) {
|
|
break;
|
|
}
|
|
} else {
|
|
out.push(undefined);
|
|
}
|
|
}
|
|
if (n_matches == 0) {
|
|
msg.token_parser.on_error();
|
|
}
|
|
this.send(out);
|
|
});
|
|
}
|
|
RED.nodes.registerType("parser-consume", ConsumaToken);
|
|
|
|
}
|