A very-lightweight rule engine for DB data sources.
It evaluates simple, human-readable rules defined in standard JavaScript objects - with async DB operations in mind.
This is a new module that I just created. If you are interesed in using the package or you have an idea for a new feature, contact me on the GitHub page.
Basic Philosophy:
- 🧩 Keep rule definitions simple and intuitive.
- ⚡ Make it straightforward to connect to async/DB operations.
- ✨ Add features without sacrificing simplicity and readibility.
I welcome feature requests and suggestions for use cases I might not have considered. The goal is to keep the rule definitions simple and intuitive while adding powerful features.
$ npm i mini-rule-engineHere's a quick example of how to define parameters, create a rule, and evaluate it.
1. Create a new engine instance, and define the data sources
import RuleEngine from 'mini-rule-engine';
// A parameter is a piece of data that the engine can check.
// The getter function can be async (eg. read from a DB)
const re = new RuleEngine();
re.defineParameterAccessor('user', async () => ({
age: 25,
country: 'Mars Colony',
isPremium: true,
}));
re.defineParameterAccessor('orderCount', async () => 4);2. Use the engine instance
// The ruleset object can be static,
// or can be read from a DB
// (eg. voucher code, dynamic configuration, etc.)
const myRuleset = {
'user.age': { min: 18 },
'user.country': { is: 'Mars Colony' },
OR: [
{'user.isPremium': { is: true } },
{'orderCount': { max: 0 } },
]
};
// Evaluate the rule
const result = await re.evaluate(myRuleset);
console.log(`Does this user meet our criteria? ${result}`); // true
// You can also get a reason for failure
const detailedResult = await re.evaluateWithReason({ 'user.age': { min: 30 } });
if (!detailedResult.value) {
if (detailedResult.parameterName === 'user.age') {
console.log(`The user's age is too low.`);
}
} ⛁ Automatic
◀ dynamic/DB
/ / read
/ /
Evaluate / ▶ of data needed
ruleset + ┌──────────────┐ for evaluation
params (call) ────────▶ │ │
│ RuleEngine │
│ instance │
(return value) ◀───────── │ │
evaluation └──────────────┘
result
min: Minimum valuemax: Maximum valueis: Equal - exact matchnot: Not equalunder: Less thanover: Greater than
There are two ways to use the logical 'OR' operator:
Simple - applied to a single parameter:
const ruleset = {
'myStatus': { OR: [
{ is: -1 },
{ min: 1, max: 10 }
]},
};Compound - applied to multiple differentparameters:
const ruleset = {
OR: [
{'user.isPremium': { is: true } }
{
'user.age': { min: 18 },
'orderCount': { max: 0 }
}
]
};Note: The 'OR' operator in both cases expects an array of objects.
The logical AND operation is implied when listing different rules in the ruleset. Therefore, no AND operatoror is defined.
The parameter and the compared limit value must have matching types to get a true result.
Supported data types: number, string, boolean, object, null.
If a parameter represents an object, this object must be a plain JS object (for security reasons). Only its own properties can be accessed (incl. getter functions).
You can use dot notation to access its properties:
const ruleset = {
'user.age': { min: 18 },
'user.country': { is: 'Mars Colony' }
};The getter functions define how to get the correspondingparameter value for an evaluation run.
The evaluation is always async. If the getter functions defined in defineParameterAccessor() are async, the evaluation will resolve immediately.
For each evaluation:
-
Only those getter functions are called, that are referenced in the evaluated ruleset.
-
Each getter function is called only once, regardless of how many times it is referenced in the ruleset. The same value will be reused for each rule.
The getter functions are defined as follows, before running any evaluations:
re.defineParameterAccessor('parameterName', getterFunction);async function getterFunction(params, meta) {...}-
meta: An object containing information about the how is the parameter used in the ruleset. This can be useful for example to limit database reads when counting objects.-
meta.accessorName(string): The name of the parameter (defined indefineParameterAccessor()) for which the getter was called.
In the case the getter returns an object, and the ruleset evaluates an object parameter, this string contains the part before the first dot. -
meta.constraintValues(array of any): All the values (operands) the parameter is being compared against in the ruleset. -
meta.childrenConstraintValues(object): Only if the parameter is accesing an object's children (eg.:'myObject.childA').
The keys list all the descendants that are being accessed in the ruleset. Each key contains an array of the corresponding constraint values (as inmeta.constraintValues).
-
-
params: Is a value or an object, that is passed directly from there.evaluate()orre.evaluateWithReason()functions (thegetterParamsparameter):
async evaluateWithReason(parameterConstraintsObject, getterParams) {}This can contain for example a userId.
Setup
const re = new RuleEngine();
re.defineParameterAccessor('user', userGetter);
re.defineParameterAccessor('orderCount', orderCountGetter);
re.defineParameterAccessor('currentOrder', currentOrderGetter);
const ruleset = {
'user.age': {
min: 18,
max: 65
},
'user.eyes.left': { not: 'red' },
OR: [
{
'user.eyes.left': { is: 'black' },
'user.age': { max: 22 }
},
{
'user.eyes.left': { not: 'black' }
}
],
'orderCount': {
min: 1
}
};
const getterParams = {
userId: 'rxzUyV7qc5',
currentOrderId: 'mDyNy3ZmnR7g'
}
const result = await re.evaluateWithReason(ruleset, getterParams);The getter functions are called with the following parameters
async function userGetter(params, meta) {...}:
params = {
userId: 'rxzUyV7qc5',
currentOrderId: 'mDyNy3ZmnR7g'
}
meta = {
accessorName: 'user',
constraintValues: [],
childrenConstraintValues: {
'age': [18, 65, 22],
'eyes.left': ['red', 'black']
}
}async function orderCountGetter(params, meta) {...}:
params //is the same
meta = {
accessorName: 'orderCount',
constraintValues: [1]
}async function currentOrderGetter(params, meta) {...}:
is not called.
'REParameterError': If the parameter definition encounters a mistake/error in its inputs, it throws.
The evaluation only throws, if it cannot be completed with a meaningful result.
-
'RERuleSyntaxError': This error is thrown, if the ruleset object contains an error. (Eg. an invalid operator) -
'RETypeError': This error is thrown, if a parameter is evaluated to a data type, that cannot be accepted. (Ie. the getter function's return value is incompatible with the given rule, eg. primitive vs. object.)
Note: Comparing different primitive values (e.g. number and string) will not throw, it will simply return false, per JS's strict equality comparison.
Go to Issue Reporting on mini-rule-engine ➜
All contributions, ideas and encouragements are welcome!