A plugin that automatically loads hapi server methods for you. Never type server.method(....)
again!
npm install hapi-method-loader
server.register({
register: require('hapi-method-loader'),
options: {}
});
Will cause hapi to scan the methods directory and import all the files it finds there as server methods.
Each method should be a file in the methods directory. Sub directories may be used for nested methods. File name will dictate method name.
- Each file should export a method function, which can take any parameters you want, return any value you want, and can be async or synchronous. Inside the function the
this
keyword will be bound to the server. - Optionally you can include an options object which will be passed on to hapi's server.method function.
- Optionally you can include a Joi schema that will be read by hapi-docs and made available in the server documentation.
- Optionally you can include a description string that will be read by hapi-docs.
Example Method File:
const Joi = require('@hapi/joi');
module.exports = {
method: function(name) {
// 'this' will be bound to the server:
this.log(`Hello ${name}!`);
},
options: {
cache: {
expiresIn: 60 * 60 * 1000
}
},
schema: Joi.object({
name: Joi.string().required()
}),
description: 'Greets the user by name'
};
Example Directory Layout:
-methods/
-hello.js
-world.js
|-data/
|-dump.js
|-db/
|- fetch.js
|- put.js
Will result in the following server methods:
- server.methods.hello()
- server.methods.world()
- server.methods.data.dump()
- server.methods.data.db.fetch()
- server.methods.data.db.put()
The following options can be passed when the plugin is registered with hapi:
-
path
By default hapi-method-loader will look for your methods in a directory named methods inside your current working directory (process.cwd()), but you can use path to specify a different directory to scan for methods.
-
prefix
By default the loaded methods will be available at
server.methods.<methodName>
. But you can specify a prefix and the plugin will make the functions available atserver.methods.<prefix>.<methodName>
. -
verbose
When true, will print out information about each method as it is loaded. Default is false.