How to create node.js library

 

From the post mysql access from node.js, you’re going to build your own node.js library. Don’t worry, it’s very simple when using javascript namespace…..


 

To do before

mysql server installed;
– know what node.js is (see blog post Comprendre node.js)
node.js installed (see blog post on Installer node.js sous Windows);
– read post mysql access from node.js;
– read post Les namespace javascript.

 

Existing code

The next code runs sq query (SELECT * FROM test) with mysql library et displays the result in javascript console.

The example below uses mysql library without warning :
– instanciate mysql object ;
– run sql queries and return the result from a connection.

var mysql = require('mysql');

var mySqlClient = mysql.createConnection({
  host     : "localhost",
  user     : "user",
  password : "password",
  database : "mysqlTest"
});

var selectQuery = 'SELECT * FROM test';

mySqlClient.query(
  selectQuery,
  function select(error, results, fields) {
    if (error) {
      mySqlClient.end();
      return;
    }
    
    console.log(fields.length);
    if ( results.length > 0 )  { 
      var firstResult = results[ 0 ];
      console.log('id: ' + firstResult['id']);
      console.log('label: ' + firstResult['label']);
      console.log('valeur: ' + firstResult['valeur']);
    } else {
      console.log("Pas de données");
    }
    mySqlClient.end();
  }
);

 

Code refactoring with a javascript namespace

The first thing to do : move existing code inside a namespace with json coventions.

This namespace includes :
– 2 fields : mysql dedicated to node.js object initialization from mysql library and mySqlClient dedicated to database connection;
– a method connect with data connection parameters (host, user, password, database);
– a method close to close database connection;
– a method executeSelectQuery to run sql select query given as parameter and return an array result.

Modified code :

db = {
  mysql : require('mysql'),
  mySqlClient : null,

  connect : function (host, user, password, database) {
    this.mySqlClient = this.mysql.createConnection({
      host     : host,
      user     : user,
      password : password,
      database : database
    });  
  },

  close : function() {
    this.mySqlClient.end();
  },

  executeSelectQuery : function( selectQuery ) {
    this.mySqlClient.query(
      selectQuery,
      function select(error, results, fields) {
        if (error) {
          this.close();
          return;
        }

        if ( results.length > 0 )  { 
          return results;
        } else {
          return null;
        }

  }
});

 

Build node.js library from refactored code

It’s very simple to do, you only have to add the module.exportsnamespace javascript and then it will become a librairy.

it changes a small bit :

db = module.exports = {
  mysql : require('mysql'),
  mySqlClient : null,

  connect : function (host, user, password, database) {
    this.mySqlClient = this.mysql.createConnection({
      host     : host,
      user     : user,
      password : password,
      database : database
    });  
  },

  close : function() {
    this.mySqlClient.end();
  },

  executeSelectQuery : function( selectQuery ) {
    this.mySqlClient.query(
      selectQuery,
      function select(error, results, fields) {
        if (error) {
          this.close();
          return;
        }

        if ( results.length > 0 )  { 
          return results;
        } else {
          return null;
        }

  }
});

 

How to use the custom node.js library ?

Your custom library is like another node.js library. To create an instance, just use require keyword with tle complete path to your own file library.

In this case, your library named db :

var db = require('db.js');

db is an object and you can call up all the methods : connect, close, executeSqlQuery.

 

Remarques

There is no point in creating a custom library that makes same thing like node.js mysql library.

The library must be a response to a need : it specializes.
For example, a Data Access Object (DAO) provide access to your project data like save player data in a videogame.

 
[important]Comments, improvement, idea : let me know. If this post has been helpful, make comments on your favorite social networks.[/important]

 

Posté dans node.jsTaggé create node.js library, node.js library  |  1 commentaire

Une réponse à "How to create node.js library"

Répondre