json-rules-engine-schema-operator
v1.1.0
Published
An operator for json-rules-engine to evaluate a value against a JSON schema
Downloads
4
Readme
json-rules-engine-schema-operator
What's This?
It's an operator to evaluate a value against a JSON Schema for the totally awesome json-rules-engine package.
Why?
Because a JSON Schema is a predicate. A value either validates against a schema, or it doesn't. Rather than writing (and maintaining) a bunch of custom operators and bloating your codebase with them, you only need one operator - a schema operator.
Installation
npm install json-rules-engine-schema-operator
# or
yarn add json-rules-engine-schema-operator
Usage
This package is BYOV - bring your own validator (highly recommend AJV!!)
import Ajv from 'ajv';
import { Engine } from 'json-rules-engine';
import createSchemaOperator from 'json-rules-engine-schema-operator';
const ajv = new Ajv();
const validator = (subject,schema) => ajv.validate(schema,subject);
const engine = new Engine();
engine.addOperator(createSchemaOperator(validator));
and now you can do this:
engine.addRule({
conditions: {
any: [
{
fact: 'firstName',
operator: 'schema',
value: {
type: 'string',
pattern: '^J',
},
},
],
},
event: {
type: 'j_firstName',
},
});
Custom Operator Name
By default, the name of the operator added to the engine is schema
. This is configurable by passing in a custom name via the second optional parameter options
:
const name = 'jsonSchemaOperator';
engine.addOperator(validator, { name });
engine.addRule({
conditions: {
any: [
{
fact: 'firstName',
operator: name,
value: {
type: 'string',
pattern: '^J',
},
},
],
},
event: {
type: 'j_firstName',
},
});
Related
I ❤️ JSON schema and json-rules-engine both so much, that I created a package json-schema-rules-engine that works very similarly, but it relies entirely on JSON schemas for predicates (or "operators"), which greatly simplifies the concept of the rules engine.