aws

Wednesday, May 16, 2012

How to connect MySQL with Mojito


Mojito is a open source MVC framework from Yahoo! This framework is a cocktail of HTML5, CSS, JQuery, YUI and build on top of Node.js, the unique feature of Mojito application is, it works in the browsers, even if they doesn't support JavaScript, the server and client application can be written in the same language JavaScript. The framework support multiple devices, there is no need to create a separate application for Android or iPhone,  single application works on the web browser and also on the smart phone web browsers.

Mojito libraries does not ship with MySQL libraries, we need to install the node modules for MySQL and include them with Mojito.

Below command installs the node modules for MySQL. (assuming Node.js is already installed in the system).

$ npm install mysql

Once the node modules for MySQL is installed, just copy the mysql folder in the node_modules to the mojito node_modules folder. (bit hacky ).

cp -Rp /home/umatg/node/node_modules/mysql  /home/y/lib/node_modules/mojito/node_modules

Since Mojito is a MVC framework written in JavaScript, we need to write the model, view and controller code in JavaScript.  The folder structure for a Mojito application looks like below.  Please refer the Mojito documentation (http://developer.yahoo.com/cocktails/mojito)  for creating a Mojito project and your Mojit.

 

To establish the connection with MySQL, we need to create the MySQL client object and invoke the query method.  The methods to create the client and execute the query are in the mysql.js library file.

The MySQL client object has to be created in the model and the methods in the model can be invoked from the controller and data sent to view in the form of a JSON.

The code below, establishes the connection and query the product table in the ads database in MySQL.

/* models/foo.server.js */
YUI.add('DashboardModel', function(Y) {
    var mysqlCli =require('mysql');
    var mysqlClient = mysqlCli.createClient({
        'host' : 'localhost',
        'port' : 3306,
        'user' : 'root',
        'password' : 'root'
    });

/**
 * The DashboardModel module.
 *
 * @module Dashboard
 */

    /**
     * Constructor for the DashboardModel class.
     *
     * @class DashboardModel
     * @constructor
     */
    Y.mojito.models.DashboardModel = {

        init: function(config) {
            this.config = config;
        },

        /**
         * Method that will be invoked by the mojit controller to obtain data.
         *
         * @param callback {Function} The callback function to call when the
         *        data has been retrieved.
         */
        getProduct: function(callback){
          mysqlClient.query(
            'SELECT * FROM ads.product',
            function selectCb(error, results, fields) {
              if (error) {
                  console.log('getProduct Error: ' + error.message);
                  mysqlClient.end();
                  return;
              }
              var result ={
                      meta:{
                          totalRecords: results.length
                      }
                };
              result.results = results;
              callback(result);
          });
        } 

    };

}, '0.0.1', {requires: []});

We are creating the MySQL client object by invoking the createClient() method from the mysql reference object, by passing the connection details.  Here the password is hard-coded, we can also encrypt the password and retrieve it from a file.

The query to select the products from the table executed by invoking the query method by passing the SQL Select statement and invoking the selectCb callback function.  The result of the query is sent back to the callback in the form of JSON.

Reference: