Package Exports
- json-expression-eval
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (json-expression-eval) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
json-expression-eval
A Node.js module that evaluates a json described boolean expressions using dynamic functions and a given context.
The module is strictly typed, ensuring that passed expressions are 100% valid at compile time.
This module is especially useful if you need to serialize complex expressions (to be saved in DB for example)
Installation
npm install json-expression-eval
Or
yarn add json-expression-eval
Usage
Please see tests and examples dir for more usages and example (under /src)
import { Expression, evaluate } from 'json-expression-eval';
interface IExampleContext {
userId: string;
times: number;
}
const exampleContext: IExampleContext = {
userId: 'a2@b.com',
times: 5,
};
const functionsTable = {
countRange: ([min, max]: [number, number], context: IExampleContext): boolean => {
return context.times >= min && context.times < max;
},
};
const expression: Expression<IExampleContext, typeof functionsTable> = {
or: [
{
userId: 'a@b.com',
},
{
and: [
{
countRange: [2, 6],
},
{
userId: 'a2@b.com',
},
],
},
],
};
console.log(evaluate(expression, exampleContext, functionsTable)); // true
Expression
There are 4 types of operators you can use (evaluated in that order of precedence):
and
- accepts a non empty list of operatorsor
- accepts a non empty list of operatorsnot
- accepts another operator<user defined funcs>
- accepts any type of argument and evaluated by the user defined functions and given context.<compare funcs>
- operates on one of the context properties and compare it to a given value.{property: {op: value}}
- available ops:
gt
- >gte
- >=lt
- <lte
- <=eq
- ===neq
- !==
- available ops:
{property: value}
- compares the property to that value (shorthand to the
eq
op)
- compares the property to that value (shorthand to the
Note that nested properties in the context are also supported starting version 3
Example expressions, assuming we have the user
and maxCount
user defined functions in place can be:
{
"or":[
{
"not":{
"user":"a@b.com"
}
},
{
"maxCount":1
},
{
"times": { "eq" : 5}
},
{
"country": "USA"
}
]
}