I am new to Hapi.js and I am stuck a point trying to figure out how can we load plugins in order in a Hapi.js setup.
For example: I have 2 plugins Plugin1 and Plugin2. Lets say Plugin2 is dependent on Plugin1 and cannot run until Plugin1 is executed.
It seems like loading these plugins in 2 separate server.register methods or with a single server.register (with array of plugins) seems to be executing the plugins code in parallel...
So, can some one help me with how can I load plugins in order...thanks in advance
You have a few options available to you.
You could take a look at Glue. You can use the array syntax for plugins to load plugins in a specific order:
var Glue = require('glue');
var manifest = {
server: {
cache: 'redis'
},
connections: [
{
port: 8000,
labels: ['web']
},
{
port: 8001,
labels: ['admin']
}
],
plugins: [
{ 'Plugin1': null },
{ 'Plugin2': null }
]
};
var options = {
relativeTo: __dirname
};
Glue.compose(manifest, options, function (err, server) {
if (err) {
throw err;
}
server.start(function () {
console.log('Hapi days!');
});
});
This is same as doing the following without the use of Glue:
server.register(require('Plugin1'), function (err) {
server.register(require('Plugin2'), function (err) {
server.start(function () {
console.log('Hapi days!');
});
});
});
Having order-dependent plugins is messy though and hapi offers a better way to fix this. You can use server.dependency()
to explictly express a plugin's dependency on another plugin. So inside Plugin2 you could do:
var ready = function (server, next) {
server.route({
...
});
next();
};
exports.register = function (server, options, next) {
server.dependency('Plugin1', ready);
next();
};
exports.register.attributes = {
name: 'Plugin2',
version: '0.0.1'
};
With this approach, it doesn't matter about the plugin registration order. This is great for big apps where there's lot of plugins worked on by different people or teams.
You will want to use server.dependency
as a solution.
With it, you can declare a plugin dependent upon another and if the dependency is missing (or you accidentally create a circular dependency) your server will throw.
With this, you have an opportunity to use the after
function to delay execution of code in Plugin2 that must wait until Plugin1 is loaded.
You can also see discussion titled "Inconsistent plugin load order" on the glue github repo or this one called "Server start can fail due to plugins not loaded in the right order" from aqua for additional info and details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With