Plugin to autoload handlers for hapi.js based on glob patterns.
Note: This package was previously published as
hapi-handlers. The scoped package@ar4mirez/hapi-handlersis the actively maintained version.
- Node.js >= 18.0.0
- @hapi/hapi >= 21.0.0
npm install @ar4mirez/hapi-handlersconst Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({ port: 3000 });
await server.register({
plugin: require('@ar4mirez/hapi-handlers'),
options: {
includes: 'path/to/**/*Handler.js'
}
});
// Your handlers are now available
server.route({
method: 'GET',
path: '/hello',
handler: {
helloHandler: {
message: 'Hello World!'
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
init();await server.register({
plugin: require('@ar4mirez/hapi-handlers'),
options: {
includes: [
'handlers/**/*.js',
'api/**/handler.js'
],
ignores: ['**/*.test.js']
}
});const manifest = {
server: {
port: 3000
},
register: {
plugins: [
{
plugin: '@ar4mirez/hapi-handlers',
options: {
includes: 'handlers/**/*.js',
relativeTo: __dirname
}
}
]
}
};- Type:
string|string[] - Description: The glob pattern(s) to match handler files.
// Single pattern
includes: 'handlers/**/*.js'
// Multiple patterns
includes: ['handlers/**/*.js', 'api/**/handler.js']- Type:
string|string[] - Description: Pattern(s) to exclude from matching.
ignores: ['**/*.test.js', '**/*.spec.js']- Type:
string - Default:
process.cwd() - Description: The base directory for resolving patterns.
relativeTo: __dirnameHandler files should export a function that returns a hapi handler function:
// handlers/userHandler.js
'use strict';
module.exports = (route, options) => {
// route: the hapi route configuration
// options: options passed from route handler config
return (request, h) => {
return {
message: options.message || 'Default message',
user: request.params.id
};
};
};server.route({
method: 'GET',
path: '/user/{id}',
handler: {
userHandler: {
message: 'User details'
}
}
});module.exports = (route, options) => {
return async (request, h) => {
const user = await fetchUser(request.params.id);
return user;
};
};Version 4.0.0 has breaking changes to support hapi v21+:
// v2/v3 (hapi v13-v16)
server.register({
register: require('@ar4mirez/hapi-handlers'),
options: { ... }
}, callback);
// v4 (hapi v21+)
await server.register({
plugin: require('@ar4mirez/hapi-handlers'),
options: { ... }
});// v2/v3
module.exports = (route, options) => {
return (request, reply) => {
return reply({ message: 'Hello' });
};
};
// v4
module.exports = (route, options) => {
return (request, h) => {
return { message: 'Hello' };
// or: return h.response({ message: 'Hello' });
};
};// v2/v3
const server = new Hapi.Server();
server.connection({ port: 3000 });
// v4
const server = Hapi.server({ port: 3000 });See CONTRIBUTING.md for guidelines.
MIT - see LICENSE for details.