lholmquist
lholmquist

Reputation: 143

Hapi,js - Proper way to include a plugin inside a plugin

I have this Hapi.js server that requires 2 endpoints to do Basic auth(using the hapi-auth-basic module). Each endpoints logic for checking the "username/password" is different, so i've broken these 2 things into their own plugins.

Currently this is how i am registering the the plugins:

...

server.register([Basic,
...
    require('./auth/register-device'),
    require('./auth/sender'),
...
], (err) => {
 ....
 

While this works, i have to make sure that the Basic plugin is also being registered.

I tried to register the Basic plugin in my plugins register method here(which i've removed and moved to the above file):

https://github.com/salty-pig/Salty-Pig/blob/master/auth/sender.js#L29 , but when i did that for both plugins, i got the error that the Basic plugin was already registered.

I guess i'm wondering what the best practice here should be. In my case, this works since i'm not distributing these "auth" plugins.

Question 2 would be: If i had a plugin that i wanted to make into a npm module, that needed to include another plugin, what are the best practices for that.

thanks

Upvotes: 0

Views: 783

Answers (1)

Francesco Pezzella
Francesco Pezzella

Reputation: 1795

If you are writing a plugin that depends on other plugins, you could use the Hapi server.dependency API:

exports.register = function (server, options, next) {
  server.dependency('hapi-auth-basic', function(server, next) {
    server.register([
      // register plugins that depend on hapi-auth-basic here
    ], (err) => {
    });
  });

  next();
};

You can supply server.dependency with an array to specify multiple dependencies.

Upvotes: 2

Related Questions