A hapi plugin that allows you to return promises in your request handlers
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:
serverroutemethod: 'GET'path: '/'replypromise;;
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:
replyHapi.errornotFound'Missing';var promise =rejectHapi.errornotFound'Missing';;replypromise;
But the following will return a generic 500 / Internal Server error:
var promise =reject'Missing';;replypromise;
This pattern allows you to easily catch and recast anticipated errors from promise-based libraries while hiding unexpected exceptions from your API consumers.