mercredi 17 octobre 2018

Pattern for injecting plugin options into Hapi route handlers defined in separate files

I am developing my Hapi app plugin and my routes are kept in a separate file to the file doing the plugin server.route call. Moreover the handlers for those routes are also in separate files. e.g.

- plugin.js
- routes.js
- handlers/
    - route1.js
    - route2.js

plugin.js is something like ....

const routes = require('./routes.js')
...
server.route(routes)

routes.js is something like ...

module.exports = [
  { 
    method: 'GET', 
    path: '/route1', 
    handler: require('./handlers/route1')
  },
  ...
]

and the handler files export functions with signature (request, h).

My route handlers (and beyond) need access to the options passed in at plugin registration but all they have access to is (request, h)

I can wrap the route definitions and each of the route handlers with functions that bring options into scope but this feels like defining conventions and folklore around how projects are structured and also I feel like it may cause problems with Javascript scoping/closure weirdness.

Is there a common Hapi library/pattern for allowing me to inject the plugin options into the route handlers e.g. allowing for a signature like (request, h, options) in a clean or well defined way?

Aucun commentaire:

Enregistrer un commentaire