This package has been deprecated

Author message:

Renamed to hapi-as-promised

hapi-promise

0.0.4 • Public • Published

hapi-promise Build Status NPM version

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

Usage

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

server.route({
  method: 'GET'
  path: '/',
  handler: function (request, reply) {
    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 (request, reply) {
  reply(Hapi.error.notFound('Missing'));
}
 
function (request, reply) {
  var promise = new Promise(function (resolve, reject) {
    reject(Hapi.error.notFound('Missing'));
  });
  reply(promise);
}

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

function (request, reply) {
  var promise = new Promise(function (resolve, reject) {
    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.

Readme

Keywords

Package Sidebar

Install

npm i hapi-promise

Weekly Downloads

0

Version

0.0.4

License

MIT

Last publish

Collaborators

  • bendrucker