Business rules as text with NEWMACRO()
NEWMACRO(text, [nocompile], [isasync]) turns a few lines of a small language into a function function(model, helpers). It is meant for rules that change more often than the code: a discount, a price, a permission check, a validation that someone who does not write JavaScript maintains in a file or in a database.
The language, as it was checked:
IF condition,ELSE IF condition,ELSEandFI(the end of the condition) work as in a text-based rule. Conditions use>,<,>=,<=,=andAND/OR.RETURN valueends the macro with a value.YESandNO(alsoTRUE,FALSE,OK) are booleans, text between quotes is text and numbers are numbers.- A word is a property of the model, written in lower case:
agereadsmodel.age, andtotal = price * qtywritesmodel.total. NAME(arguments)calls a helper, the function with that name (lower case) in thehelpersobject you pass; inside itthisis the model. Withisasyncset totruethe macro is an async function and awaits the helpers.#nameis a temporary variable of the run:#temp = num + 1andRETURN #temp.- Use names of several letters: a property or a variable of one letter was not recognised in the checks.
NEWMACRO() compiles the text with new Function, so a macro is code: only compile text that you wrote or that a trusted person maintains, never text that a visitor sent. With nocompile set to true it returns the JavaScript that it generates instead of the function, which is useful to see what a rule does.
const helpers = {
percent: function(value, rate) {
return value * rate / 100;
}
};
const age = NEWMACRO("IF age >= 18\n\tRETURN 'adult'\nELSE\n\tRETURN 'minor'\nFI");
const level = NEWMACRO("IF points > 100\n\tRETURN 'gold'\nELSE IF points > 50\n\tRETURN 'silver'\nELSE\n\tRETURN 'bronze'\nFI");
const access = NEWMACRO("IF active AND score >= 5\n\tRETURN yes\nFI\nRETURN no");
const total = NEWMACRO("total = price * qty\nIF qty >= 10\n\ttotal = total - PERCENT(total, 10)\nFI\nRETURN total");
const temporary = NEWMACRO("#next = count + 1\nRETURN #next");
const slow = NEWMACRO("RETURN LOOKUP(code)", false, true);
exports.install = function() {
ROUTE('POST /rules/', rules);
ROUTE('GET /source/', source);
};
async function rules($) {
const model = $.body;
$.json({
age: age(model, helpers),
level: level(model, helpers),
access: access(model, helpers),
total: total(model, helpers),
model_total: model.total,
temporary: temporary(model, helpers),
slow: await slow(model, { lookup: async code => 'found ' + code })
});
}
function source($) {
$.plain(NEWMACRO("IF points > 100\n\tRETURN 'gold'\nFI", true));
}