Loading ...
Sorry, an error occurred while loading the content.

Promises for server side code in Node.js

Expand Messages
  • Zia Khan
    Most of the client side libraries like jQuery and WinJS have implemented async promises. My job today was to implement promises on the server side i.e.
    Message 1 of 1 , May 1 9:23 AM
    • 0 Attachment
      Most of the client side libraries like jQuery and WinJS have implemented  async promises. My job today was to implement promises on the server side i.e. Node.js
       
      Read the following link to understand promises which is implemented by the q module of Node.js:
      http://howtonode.org/promises

      In my application in the panacloud.js module I implement promises which are consumed in app.js:
       
      Note: I am tired and done for today, u should do nodding for the night )


      //************************************************************
      // app.js main express module
      //************************************************************

      var express = require('express')
      , routes = require('./routes');
      var pc = require('./panacloud.js');
      var app = module.exports = express.createServer();
      // Configuration
      app.configure(function(){
      app.set('views', __dirname + '/views');
      app.set('view engine', 'ejs');
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(app.router);
      app.use(express.static(__dirname + '/public'));
      });
      app.configure('development', function(){
      app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
      });
      app.configure('production', function(){
      app.use(express.errorHandler());
      });
      app.listen(3000, function(){
      console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
      });
      // Routes
      app.get('/api/isregistered/:fbid', function(req, res){
      if(req.params.fbid){
      var promise = pc.isRegisteredAsync(req.params.fbid);
      promise.then(function(data){
      res.send(data);
      }, function(err){
      res.send(err);
      });
      } else {
      res.send({status:"nok", message:"Incomplete Data in request"});
      }
      });

      app.post('/api/register', express.bodyParser(), function(req, res) {
      if (req.body && req.body.fbid && req.body.pcid && req.body.fbtoken) {
      pc.registerAsync(req.body.fbid, req.body.pcid, req.body.fbtoken).then(function(data){
      res.send(data);
      }, function(err) {
      res.send(err);
      });
      } else {
      res.send({status:"nok", message:"Incomplete Data in request"});
      }
      });

      app.get('/', routes.index);



      //************************************************************
      // panacloud.js module
      //************************************************************

      /**
      * Created with JetBrains WebStorm.
      * User: zia
      * Date: 4/21/12
      * Time: 4:30 PM
      * To change this template use File | Settings | File Templates.
      */
      //http://howtonode.org/promises
      //https://github.com/kriskowal/q
      var q = require('q');
      //http://groups.google.com/group/mongoose-orm/browse_thread/thread/3207ec40b672ca3d?pli=1
      var mongoose = require('mongoose');
      mongoose.connect('mongodb://localhost/panaclouddb');
      var Schema = mongoose.Schema
      , ObjectId = Schema.ObjectId;
      var User = new Schema({
      fbid : { type: String, index: true }
      , pcid : { type: String, index: true }
      , fbtoken : String
      , name : String
      , firstname : String
      , lastname : String
      , lastupdate : { type: Date, default: Date.now }
      });
      var UserModel = mongoose.model('User', User);

      exports.isRegisteredAsync = function (fbid) {
      var deferred = q.defer();
      UserModel.findOne({ fbid: fbid}, function (err, doc){
      //doc is a Document
      if(err){
      deferred.reject( { status: "nok", errormsg: "database error", errobj: err } );
      } else {
      if(doc){
      deferred.resolve( {status:"ok", isRegistered: true, fbid: doc._doc.fbid, pcid: doc._doc.pcid} );
      } else {
      deferred.resolve( {status:"ok", isRegistered: false} );
      }
      }
      });
      return deferred.promise;
      };
      exports.registerAsync = function (fbid, pcid, fbtoken) {
      var deferred = q.defer();
      var u1 = new UserModel();
      u1.pcid = pcid;
      u1.fbid = fbid;
      u1.fbtoken = fbtoken;
      u1.save(function(err){
      if(err){
      deferred.reject({status:"nok", message:"Panacloud Registeration Failed", errobj: err});
      }
      else {
      console.log("Added User");
      deferred.resolve( {status:"ok", message:"Panacloud User Registered"});
      }
      });
      return deferred.promise;
      };

    Your message has been successfully submitted and would be delivered to recipients shortly.