node-firebird + promises

327 views
Skip to first unread message

d.gi...@gmail.com

unread,
Aug 13, 2015, 4:52:05 AM8/13/15
to node-firebird
Hello,

I wrote Node module that connects to the database Firebird with node-Firebird and q promises. I'm not entirely happy with the result but I have no idea how to simplify it further. I'm still green in js programming:) This is my module:


var
   fb = require("node-firebird"),
   Q = require('q'),            
   db;

function fb_disconnect() {
   db.detach(
      function(){
         console.log("db disconnected.");
      }
   );
};

function fb_query(connectiondata, sql, params, callback){
   var def = Q.defer();
   (Q.denodeify(fb.attach))(connectiondata).then(function(dbconn){
      db = dbconn;
      console.log("db connected.");
      db.query(sql,
         params,
         function(err, result){
            err ? def.reject(err) : def.resolve(result);
         }
      );
   }).fin(function () {
      fb_disconnect();
   });
   return def.promise.nodeify(callback);
}

function fb_seq_query(promise, sql, params, callback){
   var def = Q.defer();
   promise.then(function(dbconn){
      if(!db){db = dbconn;}
      console.log("db connected.");
      db.query(sql,
         params,
         function(err, result){
            err ? def.reject(err) : def.resolve(result);
         }
      );
   });
   return def.promise.nodeify(callback);
}

function fb_seq_queries(connectiondata, sqls, params, callback){
   var def = Q.defer();
   var promise = (Q.denodeify(fb.attach))(connectiondata);
   var i = 0;
   sqls.forEach(function(sql){
      fb_seq_query(promise, sql, params[i], callback[i]);
      i++;
   });
   promise.fail(function (err) {
      console.log(err);
   }).fin(function () {
      fb_disconnect();
   });
   return def.promise.nodeify(callback);  
}

module.exports = {
   query: function(connectiondata, sql, params, callback){
      fb_query(connectiondata, sql, params, callback);
   },
   seq_queries: function(connectiondata, sqls, params, callback){
      fb_seq_queries(connectiondata, sqls, params, callback);
   }
}

/*------------------------------------------------
example of use:
var fb_mod = require('./module');
fb_mod.query(getOptions(),'SELECT * FROM TABLE',[],function(err,result){
   console.log(result);
})
------------------------------------------------*/


Thanks in advance for all the tips.
Reply all
Reply to author
Forward
0 new messages