4
\$\begingroup\$

I'm switching my code to promises - mostly as delivered by Mongoose. I use Hapi though I think something similar would apply to Express.

In my models/services I perform queries such as:

var sampleMethod = function(id, status) {
  return Model.findById(id).exec().then(function(item) {
    if(!item) return Boom.notFound(); //404

    item.status = status;
    return Mode.somethingElseThatPromises();
  }, function(err) {
    return Boom.badImplementation() // 500
  }
}

Then in a controller:

handler: function(request, reply) {
  Model.sampleMethod(request.query.id, 'pending').then(function(res) {
    reply(res).code(204); // return 404 on not found else 204 and empty
  }, function(err) {
    reply(err);
  }    
}

Alternatively I have tried this to let Hapi catch the 500

handler: function(request, reply) {
  Model.sampleMethod(request.query.id, 'pending').then(function(res) {
    reply(res);
  }).end();    
}

I feel the above are not optimized and may be extra redundant and/or not handle all cases. I am looking for suggestions on a better controller syntax. I am not super familiar with Mongoose's promise implementation either so might be missing something.

I should add that my ultimate goal is extra lean controllers with a nice Boom usage. I generally just throw a 500 when the database does something weird (Hapi does catch these) so open to suggestions in general.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.