node-rules
node-rules copied to clipboard
consider use node's vm module instead of eval when using fromJSON
no need to add details for why eval is evil so i think a better solution and more safety is to use the vm module.
example implementation (it works):
RuleEngine.prototype.fromJSON = function(rules) {
var sandbox = {
condition: undefined,
consequence: undefined
};
this.init();
if (typeof(rules) == "string") {
rules = JSON.parse(rules);
}
if (rules instanceof Array) {
rules = rules.map(function(rule) {
sandbox = {
condition: undefined,
consequence: undefined
};
vm.runInNewContext("condition = (" + rule.condition + ")", sandbox);
vm.runInNewContext("consequence = (" + rule.consequence + ")", sandbox);
rule.condition = sandbox.condition;
rule.consequence = sandbox.consequence;
return rule;
});
} else if (rules !== null && typeof(rules) == "object") {
vm.runInNewContext("condition = (" + rule.condition + ")", sandbox);
vm.runInNewContext("consequence = (" + rule.consequence + ")", sandbox);
rule.condition = sandbox.condition;
rule.consequence = sandbox.consequence;
}
this.register(rules);
};