Autoload Handlers for HapiJS.
npm install hapi-handlers



Plugin to autoload handlers for hapi.js based on glob patterns.
- Node.js >= 18.0.0
- @hapi/hapi >= 21.0.0
``bash`
npm install hapi-handlers
`javascript
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({ port: 3000 });
await server.register({
plugin: require('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();
`
`javascript`
await server.register({
plugin: require('hapi-handlers'),
options: {
includes: [
'handlers/*/.js',
'api/**/handler.js'
],
ignores: ['*/.test.js']
}
});
`javascript`
const manifest = {
server: {
port: 3000
},
register: {
plugins: [
{
plugin: 'hapi-handlers',
options: {
includes: 'handlers/*/.js',
relativeTo: __dirname
}
}
]
}
};
- Type: string | string[]
- Description: The glob pattern(s) to match handler files.
`javascript
// Single pattern
includes: 'handlers/*/.js'
// Multiple patterns
includes: ['handlers//*.js', 'api//handler.js']
`
- Type: string | string[]
- Description: Pattern(s) to exclude from matching.
`javascript`
ignores: ['/.test.js', '/.spec.js']
- Type: stringprocess.cwd()
- Default:
- Description: The base directory for resolving patterns.
`javascript`
relativeTo: __dirname
Handler files should export a function that returns a hapi handler function:
`javascript
// 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
};
};
};
`
`javascript`
server.route({
method: 'GET',
path: '/user/{id}',
handler: {
userHandler: {
message: 'User details'
}
}
});
`javascript`
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+:
`javascript
// v2/v3 (hapi v13-v16)
server.register({
register: require('hapi-handlers'),
options: { ... }
}, callback);
// v4 (hapi v21+)
await server.register({
plugin: require('hapi-handlers'),
options: { ... }
});
`
`javascript
// 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' });
};
};
`
`javascript
// 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.