@modernpoacher/rules-runner

A business rules engine for Node

Usage no npm install needed!

<script type="module">
  import modernpoacherRulesRunner from 'https://cdn.skypack.dev/@modernpoacher/rules-runner';
</script>

README

@modernpoacher/rules-runner

Encapsulate rules in an easily comprehended JSON/JavaScript object literal format.

Install

npm i -P @modernpoacher/rules-runner

Examples

if the conditions are met then will execute.

const RulesRunner = require('@modernpoacher/rules-runner')

const config = {
  'Must be 16 or older if no adult is present': {
    if: {
      'person.age': {
        lessThan: 16
      },
      'person.adultPresent': false
    },
    then: {
      'person.error': 'Must be 16 or older if no adult is present',
      'errors.all[]': 'person'
    }
  },
  'Must be employed': {
    if: {
      'company.isEmployed': false
    },
    then: {
      'company.error': 'Must be employed',
      'errors.all[]': 'company'
    }
  }
}

const rulesRunner = new RulesRunner(config)

const values = {
  person: {
    age: 15,
    adultPresent: false
  },
  company: {
    isEmployed: false
  }
}

rulesRunner.run(values)

assert.equal(values.person.error, 'Must be 16 or older if no adult is present')
assert.equal(values.company.error, 'Must be employed')
assert.deepEqual(values.errors.all, ['person', 'company'])

if the conditions are not met otherwise will execute.

const RulesRunner = require('@modernpoacher/rules-runner')

const config = {
  'Person will be in house if person is tired or hungry': {
    if: {
      'person.age': {
        lessThan: 16
      },
      'person.adultPresent': false
    },
    then: {
      'person.location': 'house'
    },
    otherwise: {
      'person.location': 'work'
    }
  }
}

const rulesRunner = new RulesRunner(config)

const values = {
  person: {
    age: 17,
    adultPresent: true
  }
}

rulesRunner.run(values)

assert.equal(values.person.location, 'work')

Comparators

  • equals
'person.exists': true
'person.firstName': 'John'
'person.age': 21
  • boolean
'person.exists': false
  • between
'person.age': { between: [1, 20] }
  • contains
'person.name': { contains: 'Jr' }
  • lessThan
'person.age': { lessThan: 21 }
  • greaterThan
'person.age': { greaterThan: 20 }
  • oneOf
'person.state': { oneOf: ['CA', 'TX', 'NY'] }
  • anyOf
'person.state': { anyOf: ['CA', 'TX', 'NY'] }
  • allOf
'person.state': { allOf: ['CA', 'TX', 'NY'] }
  • matches
'person.name': { matches: '/(john|bob|mary)/i' }
  • not
'person.state': { not: 'CA' }`
'person.state': { not: { oneOf: ['CA', 'TX'] } }