从 Bluemix 上的 Node js 应用程序调用业务规则服务

Invoke Business Rules service from Node js application on Bluemix

我在 Bluemix 上的业务规则服务上部署了我的规则集。 如何使用 API 从 Bluemix 上的 Node js 应用程序调用规则?

将业务规则服务实例绑定到应用程序后,可以使用定义如下的 invokeRulesService 方法调用规则:

 // 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();
 }