Macros
NEWMACRO() and the macro syntax.
On this page
API
method
NEWMACRO(code, [nocompile], [isasync])
Compiles a macro into a function fn(model, helpers).
NEWMACRO(code, [nocompile], [isasync])| Parameter | Type | Description |
|---|---|---|
code |
String |
The macro, one command per line (or separated by ;). |
nocompile? |
Boolean |
Returns the JavaScript code instead of a function. Default: false |
isasync? |
Boolean |
Makes an async function. Default: false |
Returns Function function(model, [helpers]), or a string with nocompile.
The function returns the value of the first RETURN that runs, or undefined. Words are read from model and name(...) calls helpers.name with the model as this. With isasync the function is async and every helper call is awaited. With nocompile you get the generated JavaScript as a string, which is useful to check a rule.
var shipping = NEWMACRO('IF weight > 10\n\tRETURN 15\nELSE IF weight > 2\n\tRETURN 8\nFI\nRETURN 4');
shipping({ weight: 5 }); // 8
var fn = NEWMACRO('RETURN rate(currency) * price', false, true);
var value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });
type
Macro syntax
Commands and values of NEWMACRO().
Macro syntax| Syntax | Meaning |
|---|---|
IF condition … ELSE IF condition … ELSE … FI | Conditions; FI closes them |
RETURN expression | Returns a value |
AND, OR | &&, || |
==, !=, >, >=, <, <=, +, -, *, / | Operators as in JavaScript |
price, order.total | Properties of the model, read in lower case |
#name | A temporary variable: #total = price * count |
name(a, b) | A helper call |
"text", 'text' | Text; a quoted number becomes a number |
TRUE, FALSE, YES, NO, NULL | Values |
// text | A comment line |
Keywords can be in any case.
IF total >= 100 AND customer.vip == YES
RETURN total * 0.9
FI
RETURN total