hapi-promise

A hapi plugin that allows you to return promises in your request handlers

hapi-promise

A hapi plugin that allows you to return promises in your request handlers. Based on miksago's hapi-promise-testing.

Register the plugin first. Then, you can call reply from any handler with a promise. Example:

server.route({
  method: 'GET'
  path: '/',
  handlerfunction (requestreply) {
    reply(promise);
  }
});

The plugin will automatically intercept all replies that are thenables (have a property then that is a function) and resolve them. You can still chain methods to your reply like code. Only the reply body itself is modified.

It also handles errors neatly. If you reject the promise with a Hapi error, that rejection will be sent as JSON as if you'd called reply directly with the error. For all other errors, an internal error will be sent. The response is fully rewritten when a promise is rejected, so any chained header methods on the original reply call will be erased.

The following two snippets will behave identically:

function (requestreply) {
  reply(Hapi.error.notFound('Missing'));
}
 
function (requestreply) {
  var promise = new Promise(function (resolvereject) {
    reject(Hapi.error.notFound('Missing'));
  });
  reply(promise);
}

But the following will return a generic 500 / Internal Server error:

function (requestreply) {
  var promise = new Promise(function (resolvereject) {
    reject('Missing'));
  });
  reply(promise);
}

This pattern allows you to easily catch and recast anticipated errors from promise-based libraries while hiding unexpected exceptions from your API consumers.