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.
this
keyword will be bound to the server.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:
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 at server.methods.<prefix>.<methodName>
.
verbose
When true, will print out information about each method as it is loaded. Default is false.