akmjenkins/json-schema-rules-engine

stupid question, how to do logical or/and?

Closed this issue · 2 comments

I am trying to evaluate the different json rules engine. Since this library uses AJV, how do you do a logical or/and? for example:

when :[
           {
               firstName: { is: { type: 'string', pattern: '^J' } },
          },
         {
                             firstName: { is: { type: 'string', pattern: '^A' } },
         }
]

I assume this is an AND operator right? how do you do an OR?

👋🏼 @hyusetiawan

From the README:

If any of the FactMaps in the object or array evaluate to true, the properties of the then clause of the rule are evaluated. If not, the otherwise clause is evaluated

So what you are assuming is a logical AND is actually a logical OR. when is an array of FactMaps and if ANY of those evaluate to true, then the engine will evaluate then.

So this is a logical OR:

{
   when: [
       { 
           firstName: { is: { type: 'string', pattern: '^A' } } 
       },
       { 
           firstName: { is: { type: 'string', pattern: '^J' } } 
       },
   ],
   then: {
     ... your actions
   },
   otherwise: {
     ... your actions
   }
}

But you can leverage JSON schema to perform your logical and/or as well by using schema composition

So you can do this as well

{
  when: [
    {
      firstName: {
         is: {
             oneOf: [
                 { type: 'string', pattern: '^J' },
                 { type: 'string', pattern: '^A' },
             ]
         }
      }
    }
  ],
  then: {
      ...your actions
   },
   otherwise: {
      ...your actions
   }
}

Finally, this library DOES NOT use AJV. Although it is recommended that you should use AJV to create your validator

@akmjenkins ah gotcha, It's clear now, thank you for the prompt answer!