Invoke Business Rules service from Node js application on Bluemix

100 views Asked by At

I have my ruleset deployed on the Business Rules service on Bluemix. How do I invoke the rules using API from my Node js application on Bluemix?

1

There are 1 answers

0
z_blue On BEST ANSWER

After binding the Business Rules service instance to the application, rules can be invoked using the invokeRulesService method defined as follows:

 // Check for Business Rules service
 var brules = null;
 //parse VCAP_SERVICES if running in Bluemix
 if (process.env.VCAP_SERVICES) {
     var env = JSON.parse(process.env.VCAP_SERVICES);
     console.log(env);
     //find the Business Rules service
     if (env["businessrules"])
     {
         brules = env['businessrules'][0]['credentials'];
         console.log(brules);
     }
     else
     {
         console.log('Please bind the Business Rules service to this application');
     }
 }
     
 function invokeRulesService(rulesetPath, inputParams, callback) {
     // check if brules is null
     if (brules == null){
         console.log("Please bind the business rules service to this application.");
         return;
     }
     var restUrl = url.parse(brules.executionRestUrl);
     var dataString = JSON.stringify(inputParams);
     // encode 'user:password' in Base64 string for basic authentication of the execution API
     var encodedCredentials = new Buffer(brules.user+':'+brules.password).toString('base64');
     headers = { 'Content-Type': 'application/json', 
                 'Content-Length': dataString.length, 
                 'Authorization': 'Basic ' + encodedCredentials // basic authentication header
     };
     var options = {
         host: restUrl.host,
         path: restUrl.path + rulesetPath,
         method: 'POST',
         headers: headers
     };
 
     var req = https.request(options, function(resp) {
         resp.setEncoding('utf-8');
         var responseString = '';
 
         resp.on('data', function(data) {
           responseString += data;
         });
 
         resp.on('end', function() {
           console.log(responseString);
           if (resp.statusCode == 200)
             var responseObject = JSON.parse(responseString);
           callback(responseObject);
         });
       });
       
       req.on('error', function(e) {
           console.log(e.message);
         });
       
       req.write(dataString);
       req.end();
 }