nimbit-software / gojson-rules-engine

go version of cache-controls json-rules-engine
ISC License
5 stars 0 forks source link

Example not running #2

Open BalaMahesh opened 1 month ago

BalaMahesh commented 1 month ago

Hello,

I am trying to run the example in my local set up.

package main

import (
    "context"
    "fmt"
    rulesEngine "github.com/nimbit-software/gojson-rules-engine/rulesengine"
)

func main() {

    rule := []byte(`{
      conditions: {
        any: [{
          all: [{
            fact: 'gameDuration',
            operator: 'equal',
            value: 40
          }, {
            fact: 'personalFoulCount',
            operator: 'greaterThanInclusive',
            value: 5
          }]
        }, {
          all: [{
            fact: 'gameDuration',
            operator: 'equal',
            value: 48
          }, {
            fact: 'personalFoulCount',
            operator: 'greaterThanInclusive',
            value: 6
          }]
        }]
      },
      event: {  // define the event to fire when the conditions evaluate truthy
        type: 'fouledOut',
        params: {
          message: 'Player has fouled out!'
        }
      }
    }`)

    // CONTEXT FOR EARLY-STOPPING
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // ENGINE OPTIONS
    ep := &rulesEngine.RuleEngineOptions{
        AllowUndefinedFacts: true,
    }

    engine := rulesEngine.NewEngine(nil, ep)

    fmt.Println("%T", rule)

    engine.AddRule(rule)

    facts := []byte(`{
            "personalFoulCount": 6,
            "gameDuration": 40,
            "name": "John",
            "user": {
                "lastName": "Jones"
            }
        }`)

    // THE RUN FUNCTION ACCEPTS BOTH A MAP AND A BYTE ARRAY
    // - []byte (byte array offers slightly better performance) under the hood github.com/buger/jsonparser is used to parse it into the almanac
    // - map[string]interface{}
    res, err := engine.Run(ctx, facts)
    fmt.Println(res, err)
}

and getting this error

panic: interface conversion: interface {} is []uint8, not map[string]interface {}

goroutine 1 [running]:
github.com/nimbit-software/gojson-rules-engine/rulesengine.(*Engine).AddRule(0x1400013c210, {0x104bbffe0?, 0x1400011e570?})
nimbit-software commented 1 month ago

Sorry about that. There was some issues in the example. I just updated it and it should work.

the rule should be Unmarshaled before its added. And has to be a valid JSON

    var ruleMap map[string]interface{}
    if err := json.Unmarshal(rule, &ruleMap); err != nil {
        panic(err)
    }