Skip to content

Feature/add value pipes support #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions examples/10-facts-with-pipes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
'use strict'
/*
* This is a basic example demonstrating a condition that applies pipes to facts' values
*
* Usage:
* node ./examples/10-fact-comparison.js
*
* For detailed output:
* DEBUG=json-rules-engine node ./examples/10-fact-comparison.js
*/

require('colors')
const { Engine } = require('json-rules-engine')

async function start () {
/**
* Setup a new engine
*/
const engine = new Engine()

/**
* Rule for determining if account can affor a gift card product with a 50% discount
*
* customer-account-balance >= $50 gift card
*/
const discount = 0.5
const rule = {
conditions: {
all: [{
// extract 'balance' from the 'partner' account type
fact: 'account',
path: '$.balance',
params: {
accountType: 'partner'
},

operator: 'greaterThanInclusive', // >=

// "value" in this instance is an object containing a fact definition
// fact helpers "path" and "params" are supported here as well
value: {
fact: 'product',
path: '$.price',
pipes: [ { name: 'scale', args: [discount]}],
params: {
productId: 'giftCard'
}
}
}]
},
event: { type: 'customer-can-partially-afford-gift-card' }
}
engine.addRule(rule)

engine.addFact('account', (params, almanac) => {
// get account list
return almanac.factValue('accounts')
.then(accounts => {
// use "params" to filter down to the type specified, in this case the "customer" account
const customerAccount = accounts.filter(account => account.type === params.accountType)
// return the customerAccount object, which "path" will use to pull the "balance" property
return customerAccount[0]
})
})

engine.addFact('product', (params, almanac) => {
// get product list
return almanac.factValue('products')
.then(products => {
// use "params" to filter down to the product specified, in this case the "giftCard" product
const product = products.filter(product => product.productId === params.productId)
// return the product object, which "path" will use to pull the "price" property
return product[0]
})
})

/**
* Register listeners with the engine for rule success and failure
*/
let facts
engine
.on('success', (event, almanac) => {
console.log(facts.userId + ' DID '.green + 'meet conditions for the ' + event.type.underline + ' rule.')
})
.on('failure', event => {
console.log(facts.userId + ' did ' + 'NOT'.red + ' meet conditions for the ' + event.type.underline + ' rule.')
})

// define fact(s) known at runtime
const productList = {
products: [
{
productId: 'giftCard',
price: 50
}, {
productId: 'widget',
price: 45
}, {
productId: 'widget-plus',
price: 800
}
]
}

let userFacts = {
userId: 'washington',
accounts: [{
type: 'customer',
balance: 500
}, {
type: 'partner',
balance: 30
}]
}

// compile facts to be fed to the engine
facts = Object.assign({}, userFacts, productList)

// first run, user can afford a discounted gift card
await engine.run(facts)

// second run; a user that cannot afford a discounted gift card
userFacts = {
userId: 'jefferson',
accounts: [{
type: 'customer',
balance: 30
}, {
type: 'partner',
balance: 10
}]
}
facts = Object.assign({}, userFacts, productList)
await engine.run(facts)
}
start()
/*
* OUTPUT:
*
* washington DID meet conditions for the customer-can-afford-gift-card rule.
* jefferson did NOT meet conditions for the customer-can-afford-gift-card rule.
*/
96 changes: 74 additions & 22 deletions src/condition.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,28 @@ import debug from './debug'
import isObjectLike from 'lodash.isobjectlike'

export default class Condition {
constructor (properties) {
constructor(properties) {
if (!properties) throw new Error('Condition: constructor options required')
const booleanOperator = Condition.booleanOperator(properties)
Object.assign(this, properties)
if (booleanOperator) {
const subConditions = properties[booleanOperator]
if (!(Array.isArray(subConditions))) {
if (!Array.isArray(subConditions)) {
throw new Error(`"${booleanOperator}" must be an array`)
}
this.operator = booleanOperator
// boolean conditions always have a priority; default 1
// boolean conditions always have a priority default 1
this.priority = parseInt(properties.priority, 10) || 1
this[booleanOperator] = subConditions.map((c) => {
return new Condition(c)
})
} else {
if (!Object.prototype.hasOwnProperty.call(properties, 'fact')) throw new Error('Condition: constructor "fact" property required')
if (!Object.prototype.hasOwnProperty.call(properties, 'operator')) throw new Error('Condition: constructor "operator" property required')
if (!Object.prototype.hasOwnProperty.call(properties, 'value')) throw new Error('Condition: constructor "value" property required')
if (!Object.prototype.hasOwnProperty.call(properties, 'fact'))
throw new Error('Condition: constructor "fact" property required')
if (!Object.prototype.hasOwnProperty.call(properties, 'operator'))
throw new Error('Condition: constructor "operator" property required')
if (!Object.prototype.hasOwnProperty.call(properties, 'value'))
throw new Error('Condition: constructor "value" property required')

// a non-boolean condition does not have a priority by default. this allows
// priority to be dictated by the fact definition
Expand All @@ -37,7 +40,7 @@ export default class Condition {
* @param {Boolean} stringify - whether to return as a json string
* @returns {string,object} json string or json-friendly object
*/
toJSON (stringify = true) {
toJSON(stringify = true) {
const props = {}
if (this.priority) {
props.priority = this.priority
Expand Down Expand Up @@ -68,13 +71,42 @@ export default class Condition {
return props
}

/**
* Apply the given set of pipes to the given value.
*/
_evalPipes(value, pipes, pipeMap) {
if (!Array.isArray(pipes))
return Promise.reject(new Error('pipes must be an array'))
if (!pipeMap) return Promise.reject(new Error('pipeMap required'))

let currValue = value
for (const pipeObj of pipes) {
const pipe = pipeMap.get(pipeObj.name)
if (!pipe)
return Promise.reject(new Error(`Unknown pipe: ${pipeObj.name}`))
currValue = pipe.evaluate(currValue, ...(pipeObj.args || []))
}

return currValue
}

/**
* Interprets .value as either a primitive, or if a fact, retrieves the fact value
*/
_getValue (almanac) {
_getValue(almanac, pipeMap) {
const value = this.value
if (isObjectLike(value) && Object.prototype.hasOwnProperty.call(value, 'fact')) { // value: { fact: 'xyz' }
return almanac.factValue(value.fact, value.params, value.path)
if (
isObjectLike(value) &&
Object.prototype.hasOwnProperty.call(value, 'fact')
) {
// value: { fact: 'xyz' }
return almanac
.factValue(value.fact, value.params, value.path)
.then((factValue) =>
value.pipes
? this._evalPipes(factValue, value.pipes, pipeMap)
: factValue
)
}
return Promise.resolve(value)
}
Expand All @@ -86,23 +118,43 @@ export default class Condition {
*
* @param {Almanac} almanac
* @param {Map} operatorMap - map of available operators, keyed by operator name
* @param {Map} pipeMap - map of available pipes, keyed by pipe name
* @returns {Boolean} - evaluation result
*/
evaluate (almanac, operatorMap) {
evaluate(almanac, operatorMap, pipeMap) {
if (!almanac) return Promise.reject(new Error('almanac required'))
if (!operatorMap) return Promise.reject(new Error('operatorMap required'))
if (this.isBooleanOperator()) return Promise.reject(new Error('Cannot evaluate() a boolean condition'))
if (!pipeMap && this.pipes && this.pipes.length)
return Promise.reject(new Error('pipeMap required'))
if (this.isBooleanOperator())
return Promise.reject(new Error('Cannot evaluate() a boolean condition'))

const op = operatorMap.get(this.operator)
if (!op) return Promise.reject(new Error(`Unknown operator: ${this.operator}`))
if (!op)
return Promise.reject(new Error(`Unknown operator: ${this.operator}`))

return this._getValue(almanac) // todo - parallelize
.then(rightHandSideValue => {
return almanac.factValue(this.fact, this.params, this.path)
.then(leftHandSideValue => {
return this._getValue(almanac, pipeMap) // todo - parallelize
.then((rightHandSideValue) => {
return almanac
.factValue(this.fact, this.params, this.path)
.then((leftHandSideValue) =>
this.pipes
? this._evalPipes(leftHandSideValue, this.pipes, pipeMap)
: leftHandSideValue
)
.then((leftHandSideValue) => {
const result = op.evaluate(leftHandSideValue, rightHandSideValue)
debug(`condition::evaluate <${JSON.stringify(leftHandSideValue)} ${this.operator} ${JSON.stringify(rightHandSideValue)}?> (${result})`)
return { result, leftHandSideValue, rightHandSideValue, operator: this.operator }
debug(
`condition::evaluate <${JSON.stringify(leftHandSideValue)} ${
this.operator
} ${JSON.stringify(rightHandSideValue)}?> (${result})`
)
return {
result,
leftHandSideValue,
rightHandSideValue,
operator: this.operator,
}
})
})
}
Expand All @@ -112,7 +164,7 @@ export default class Condition {
* If the condition is not a boolean condition, the result will be 'undefined'
* @return {string 'all' or 'any'}
*/
static booleanOperator (condition) {
static booleanOperator(condition) {
if (Object.prototype.hasOwnProperty.call(condition, 'any')) {
return 'any'
} else if (Object.prototype.hasOwnProperty.call(condition, 'all')) {
Expand All @@ -125,15 +177,15 @@ export default class Condition {
* Instance version of Condition.isBooleanOperator
* @returns {string,undefined} - 'any', 'all', or undefined (if not a boolean condition)
*/
booleanOperator () {
booleanOperator() {
return Condition.booleanOperator(this)
}

/**
* Whether the operator is boolean ('all', 'any')
* @returns {Boolean}
*/
isBooleanOperator () {
isBooleanOperator() {
return Condition.booleanOperator(this) !== undefined
}
}
17 changes: 17 additions & 0 deletions src/engine-default-pipes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use strict";

import Pipe from "./pipe";

const Pipes = [];

//numbers pipes
Pipes.push(new Pipe("scale", (v, factor) => v * factor));
Pipes.push(new Pipe("add", (v, r) => v + r));
Pipes.push(new Pipe("sub", (v, r) => v - r));

//strings pipes
Pipes.push(new Pipe("trim", (v) => v.trim()));
Pipes.push(new Pipe("upper", (v) => v.toUpperCase()));
Pipes.push(new Pipe("lower", (v) => v.toLowerCase()));

export default Pipes;
Loading