Search code examples
javascriptnode.jsrule-enginenode-rules

Reading Multiple Attribute in JSON using node js


I am able to validate a single JSON object, but I want to validate an array of JSON objects like below, and console the invalid Pincode city name:

var RuleEngine = require("node-rules");

var R = new RuleEngine();

var fact =
    [{
        "name": "Person",
        "website": "Udemy",
        "transactionTotal": 400,
        "cardType": "Credit Card",
        "statuscode": 200,
        "details": {
            "city": "Kirochnaya ",
            "pincode": 191015
        }
    },
    {
        "name": "Person2",
        "website": "Udemy",
        "transactionTotal": 900,
        "cardType": "Credit Card",
        "statuscode": 200,
        "details": {
            "city": "Kirochnaya ",
            "pincode": 191015
        }
    },
        {
        "name": "Person3",
        "website": "Udemy",
        "transactionTotal": 800,
        "cardType": "Credit Card",
        "statuscode": 200,
        "details": {
            "city": "Saint Petersburg",
            "pincode": 191123
        }
    }];

var rule = {
    "condition": function (R) {
        console.log(this);
        R.when(this.details.city != "Kirochnaya");
    },
    "consequence": function (R) {
        this.result = false;
        this.reason = " Failed validation bcos city name is not matched";
        R.stop();
    }
};

R.register(rule);

R.execute(fact, function (data) {
    if (data.result) {
        console.log("Valid statuscode");
    } else {
        console.log("Blocked Reason:" + data.reason);
    }
});

For the above code expected output is :

Failed validation bcos city name is not matched: Saint Petersburg 191123


Solution

  • You can loop through the array and execute the rule for each fact:

    var rule = {
        "condition": function (R) {
            console.log(this);
            R.when(this.details.city != "Kirochnaya");
        },
        "consequence": function (R) {
            this.result = false;
            this.reason = " Failed validation bcos city name is not matched: " + this.details.city + " " + this.details.pincode;
            R.stop();
        }
    };
    
    R.register(rule);
    
    fact.forEach(check => {
        R.execute(check, function (data) {
            if (data.result) {
                console.log("Valid statuscode");
            } else {
                console.log("Blocked Reason:" + data.reason);
            }
        });
    });