json-rules-engine icon indicating copy to clipboard operation
json-rules-engine copied to clipboard

Complex rule for the fact

Open suresh-webonise opened this issue 2 years ago • 2 comments

Suppose the fact is const fact={ id:1, username:'sureshk', student:[{name:'zbc',percentage:100},{name:'zb',percentage:10}], role:['coach','mentor'], sport:['hockey','base'] } and the rule should be

rule criteria => (student.name ='zbc' AND student.percentage=100) AND id=1 AND username='sureshk' AND role = 'coach' AND sport='hockey' what will the json rules for the above rule criteria and facts

suresh-webonise avatar Mar 17 '23 14:03 suresh-webonise

@suresh-webonise can you clarify the structure of the facts? Specifically the role, name, and sport. If role is an array containing multiple roles you can do a contains check. If it's a single role you can use an equality check.

For example:

const facts = {
  id:1,
  username:'sureshk',
  student: {name:'zbc',percentage:100},
  role: 'coach',
  sport:'hockey'
}

const rule = {
   condition: {
      all: [
        {
           fact: 'id',
           operator: 'equal'
           value: 1
        },
       {
          fact: 'username',
          operator: 'equal',
          value: 'sureshk'
        },
        {
           fact: 'student',
           path: '$.name',
           operator: 'equal'
           value: 'zbc'
        },
        ...
      ]
    }
}

chris-pardy avatar Nov 13 '23 11:11 chris-pardy

const fact={
  id:1,
  username:'sureshk',
  student:[{name:'zbc',percentage:100},{name:'zb',percentage:10}],
  role:['coach','mentor'],
  sport:['hockey','base']
}

const rule = {
	event: {
		type: "",
		params: {}
	},
	conditions: {
		all: [
                        {
				fact: "student",
				operator: "customContains",
				value: [ 
                                 {
                                   "field": "name",
                                   "value": "zbc",
                                   "operator": "="
                                 },
                                 {
                                   "field": "percentage",
                                   "value": 100,
                                   "operator": "="
                                 }
                                ]
			},
			{
				fact: "id",
				operator: "equal",
				value: 1
			},
			{
				fact: "username",
				operator: "equal",
				value: "sureshk"
			},
			{
				fact: "role",
				operator: "contains",
				value: "coach"
			},
			{
				fact: "sport",
				operator: "contains",
				value: "hockey"
			}
		]
	}
}

I hadn't realized that students was an array of objects. In this case, I created a custom operator that searches for an object within an array.

augustosilas avatar Nov 13 '23 11:11 augustosilas