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);
}
};
};
Like this:
Like Loading...
Related