简体   繁体   中英

How could I encapsulate request lifecycle events in Hapi.js?

I've just started out with hapi.js and I love the request lifecycle events, which each tutorial / guide I read shows them like this:

server.ext('onPreResponse', (request, reply) => {
    // ... these are great.
});

but obviously, I don't want to register them all in my server.register in my main script. I could do:

const lifecycle = require('./server/lifecycle');
server.ext('onPreResponse', lifecycle.onPreResonse);

But is there a way to encapsulate this further, to keep my main script lean and, well... clean?

The most effective way to do this, and the preferred way, it to encapsulate the functionality in a plugin. Don't think of a hapi plugin as a traditional "Plugin". It's more of just a way to better encapsulate your code.

Organizing your code into plugins does a few things for you.

  1. Forces you to more strictly encapsulate functionality
  2. Makes re-use of code easier across projects
  3. Makes loading all of your functionality into hapi much cleaner and straight forward.

Here is an example of what you're plugin could look like:

exports.register = (server, options, next) => {

  server.ext('onPreResponse', (request, reply) => {
    // ... these are great.
  });

  next()
}

exports.register.attributes = {
  name: 'great-things',
  version: '1.0.0'
}

In fact, when I'm building sites with hapi, I put all functionality into plugins in an /app/plugins directory, then break them out into separate Node.js modules if I need to reuse them across different projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM