Tech Is Hard

Credibility = Talent x Years of experience + Proven hardcore accomplishment

Functions to Create HTTP Callbacks for Mongoose


In setting up the APIs in my express application, there are many functions in which all I’m doing is sending the data passed back from my Mongoose call.  Having some functions that can set up canned mongoose callback functions is handy.  There are different functions to result in the response codes I want, depending on the context — am I getting or saving data?  The helper functions return an appropriate function to pass to Mongoose:

/**
 * Returns a foobar
 */
var getFoobar = function (q, r) {
  Foomodel
    .findById (q.params.id)
      .run (notFoundResponder ("Get foobar " + q.params.id, _.bind(r.send, r)));
};
var notFoundResponder = function (strOp, respond) {
  return function (e, doc) {
    if (doc && Object.keys(doc).length > 1) {
      console .log (strOp + " successful");
      respond (doc, 200);
    }
    else
      respond (strOp + " not found or error: " + util .inspect (doc) + " " + util .inspect (e), 404); 
  };
};
var emptyResponder = function (strOp, respond) {
  return function (e, doc) {
    if (e) 
      respond (strOp + " error: " + util .inspect (e), 500);
    else {
      console .log (strOp + " successful");      
      respond (doc, Object.keys(doc).length > 0 ? 200 : 204);
    }
  };
};
var saveResponder = function (strOp, respond) {
  return function (e, doc) {
    if (doc && Object.keys(doc).length > 1) {
      console .log (strOp + " successful");
      respond (doc, 201);
    }
    else
      respond (strOp + " not saved: " + util .inspect (doc) + " " + util .inspect (e), 500); 
  };
};
var updateResponder = function (strOp, respond) {
  return function (e, doc) {
    if (e)
      respond (strOp + " not updated: " + util .inspect (e), 500);
    else {
      console .log (strOp + " successful");
      respond (doc, 200);
    }
  };
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: