Git Product home page Git Product logo

js-rules-engine's Introduction

NPM Version CI

Rules Engine

JavaScript rules engine for validating data object structures.

Table of Contents

Features

  • ๐Ÿ’ช Easy to use chainable API.
  • ๐Ÿ’ฅ Support for infinitely nested AND / OR conditions.
  • ๐Ÿš€ Rules can be expressed in simple JSON.
  • โœ”๏ธ Customize operators with your own functions.
  • ๐Ÿ„ Access nested properties with dot notation paths.

Installation

npm install js-rules-engine --save

Usage

import { Rule } from 'js-rules-engine';

// homeWorld.name equals 'Tatooine' AND (name contains 'Skywalker' OR eyeColor is 'green')
const rule = new Rule().equals('homeWorld.name', 'Tatooine').or((sub) => {
  sub.contains('name', 'Skywalker').equals('eyeColor', 'green');
});

// object of data to evaluate rule against
const fact = {
  eyeColor: 'blue',
  homeWorld: {
    name: 'Tatooine',
  },
  name: 'Luke Skywalker',
};

rule.evaluate(fact);
// => true

Default Engine

An Engine contains all operators available to a Rule. By default, a single Engine instance is used for all Rule instances. The default Engine's operators can be customized like this:

import { defaultEngine } from 'js-rules-engine';

defaultEngine.removeOperator('greaterThan');
defaultEngine.addOperator('moreGreaterThan', myAwesomeFunction);

Override Engine

Each instance of Rule has the ability to use it's own Engine instance, overriding the default.

import { Engine, Rule } from 'js-rules-engine';

const engine = new Engine();
const rule = new Rule(null, engine);

Default Operators

Each Engine contains the follow operators by default:

  • equals
  • notEquals
  • in
  • notIn
  • contains
  • notContains
  • lessThan
  • lessThanOrEquals
  • greaterThan
  • greaterThanOrEquals

Customizing Operators

Add your own operators to an Engine. Once added, any custom Operator can be used via the Rule's add() method.

import { defaultEngine, Operator } from 'js-rules-engine';

const noop = new Operator('noop', (a, b) => true);
defaultEngine.addOperator(noop);

You can also remove an Operator.

import { defaultEngine } from 'js-rules-engine';

defaultEngine.removeOperator('noop');

Rule Conditions

The add method is a generic way to add a condition to the Rule. The conditions operator is added via it's name. The value type should match what the operator is expecting.

Param Description Type
fact Property name or dot notation path. string
operator Name of operator to use. string
value Value to compare. any

A Rule has shortcut methods for all default operators. Each method takes two arguments (fact and value) and returns the Rule instance for chaining.

Method Fact Type Value Type
equals string any
notEquals string any
in string string
notIn string string
contains string any
notContains string any
lessThan string number
lessThanOrEquals string number
greaterThan string number
greaterThanOrEquals string number

Nested conditions can be achieved with the and() / or() methods. Each methods takes one parameter, a callback function that is supplied with a nested Rule instance as the first argument, and returns the original Rule instance for chaining.

Persisting Rules

Rules can easily be converted to JSON and persisted to a database, file system, or elsewhere.

// save rule as JSON string ...
const jsonString = JSON.stringify(rule);
localStorage.setItem('persistedRule', jsonString);
// ... and hydrate rules from a JSON object!
const jsonString = localStorage.getItem('persistedRule');
const json = JSON.parse(jsonString);
const rule = new Rule(json);

Example JSON structure:

{
  "and": [
    {
      "fact": "homeWorld.name",
      "operator": "equals",
      "value": "Tatooine"
    },
    {
      "or": [
        {
          "fact": "name",
          "operator": "contains",
          "value": "Skywalker"
        },
        {
          "fact": "eyeColor",
          "operator": "equals",
          "value": "green"
        }
      ]
    }
  ]
}

Development

npm install
npm run build

js-rules-engine's People

Contributors

justinlettau avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

js-rules-engine's Issues

Console warnings "Failed to parse source map" Error: ENOENT: no such file or directory

Describe the Issue

When using the library in a Create React App typescript application, the webpack console throws 12 warnings for the package pertaining to source maps no existing for the package.

Expected behavior

Package can be used in create react app without complaining about the lack of source maps.

Steps to Reproduce


npm install -g create-react-app --template typescript
npx create-react-app my-app
cd my-app
npm install js-rules-engine
//add an import to the app.tsx for the package. 
//example: 
// import { Rule } from 'js-rules-engine';
// const rule =  new Rule();

npm start

//console should displays warnings

Other Information

package versions:

"js-rules-engine": "^1.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.8.4",

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency husky to v8

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • codecov/codecov-action v3
npm
package.json
  • ts-dot-prop ^1.4.3
  • @types/jest ^26.0.24
  • @typescript-eslint/eslint-plugin ^4.29.0
  • @typescript-eslint/parser ^4.29.0
  • eslint ^7.32.0
  • eslint-config-prettier ^8.3.0
  • husky ^7.0.1
  • jest ^27.0.6
  • prettier ^2.3.2
  • pretty-quick ^3.1.1
  • standard-version ^9.3.1
  • ts-jest ^27.0.4
  • ts-node ^10.1.0
  • typescript ^4.3.5

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.