A hapi plugin that automatically loads routes from a directory for your hapi server (never type "server.route(...)" again!)
In your main hapi directory do:
npm install hapi-route-loaderYou define routes in js files inside a nested directory structure in a 'routes' directory in your server project (file format will be explained below):
/routes
├── api
│ ├── foo.js/
│ ├── bar.js/
│ ├── baz.js/
│ ├── baz.js/
│ ├── bat/
│ ├── bif.js/
├── admin
│ ├── foo.js/
│ ├── bar.js/
├── login.js
├── logout.js
This will register the following routes with your server:
/api/foo
/api/bar
/api/baz
/api/bat/bif
/admin/foo
/admin/bar
/login
/logout
Files contain the options passed to server.route
/routes/api/myRoute.js:
exports.test={method: 'GET',handler(request,h){return'<h1> Hello World </h1>';}};Creates a GET route handler at /api/myRoute
/routes/api/myRoute.js:
exports.test={path: 'callMe',method: 'POST',handler(request,h){return{value: request.query.value};}};Since the 'path' field is specified this creates a POST route at /api/CallMe instead of /api/myRoute
To register the plugin just do:
constrouteLoader=require('hapi-route-loader');constserver=newhapi.Server({port: 8000});awaitserver.register({plugin: routeLoader.plugin, options });and this will then load the routes from the base directory
path
the path to the directory containing your route files, default is the
/routesdirectory in the current working directory (process.cwd()). For example, setting options.path to '/myRoutes' will look in/myRoutesinstead.base
the root path for all routes, by default this is '/' but you can override this. For example if 'base' is
/apiand you have a route specified at/foo.jsit will be registered as/api/fooinstead of/fooprefix
works like base, except prefix will always be at the beginning of the path
verbose
prints out verbose information about each route as it is registered, default is false
autoLoad
The route-loading function is exported by the library. By default hapi-route-loader will load and register all routes when you register the plugin. Set autoLoad to false to skip this and manually use the exported function.
routeConfig
You can specify a base routeConfig for all routes, for example:
// this will be assigned to all routesconstpre1=(request,reply)=>{return'global!';};{routeConfig: {pre: [{method: pre1,assign: 'm1'},]}}
will result in each route having the indicated pre method