Thursday, April 16, 2015

Sample code for Nodejs + Mysql REST service on IBM Bluemix

Carry on from my previous post. 

The following code provides a sample or a template for writing your own REST services which uses Nodejs to save data in MqSql database. It uses data connection pooling provided by mysql package.

Basically, this code is meant to be deployed on IBM Bluemix PaaS environment. For local execution, you would not need "cfenv" package. Instead, just run it with "express" server. The same code would work on any PaaS platform that uses Cloud Foundry underneath.

==============START OF CODE============

// This application uses express as it's web server
// for more info, see: http://expressjs.com

var express = require('express');
var http = require('http');
var mysql= require('mysql');

var pool      =    mysql.createPool({
    connectionLimit : 100, //important
    host     : 'hostname_OR_IP',
    user     : 'dbuser',
    password : 'dbuser_password',
    database : 'dbname',
    debug    :  false
});

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv

var cfenv = require('cfenv');

// create a new express server
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));


//Service method that searches for any user with firstname
app.get('/customers/:firstname', function (req, res) {
    var queryStr = "SELECT * FROM AD_CUSTOMER WHERE FNAME = '"+req.params.firstname+"'";
    console.log(queryStr);
  
    pool.getConnection(function(err,connection){
        if (err) {
          connection.release();
          res.json({"code" : 100, "status" : "Error in connection database"});
          return;
        } 

        console.log('connected as id ' + connection.threadId);
      
        connection.query(queryStr,function(err,rows){
            connection.release();
            if(!err) {
                res.json(rows);
            }         
        });

        connection.on('error', function(err) {     
              res.json({"code" : 100, "status" : "Error in connection database"});
              return;   
        });
  });
});


// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, appEnv.bind, function() {
 

// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});



==============END OF CODE============

Once deployed, this web service can be invoked with following endpoint URL:


http://<mybluemixURL>/customers/John

NOTE: In my blog, I will try to add a separate post on how to deploy these kind of Nodejs apps on Bluemix. That's altogether a different topic.



No comments:

Post a Comment