How to store routes in separate files when using Hapi?

You can create a separate file for user routes (config/routes/user.js):

module.exports = [
    { method: 'GET', path: "https://stackoverflow.com/users", handler: function () {} },
    { method: 'GET', path: '/users/{id}', handler: function () {} }
];

Similarly with cart. Then create an index file in config/routes (config/routes/index.js):

var cart = require('./cart');
var user = require('./user');

module.exports = [].concat(cart, user);

You can then load this index file in the main file and call server.route():

var routes = require('./config/routes');

...

server.route(routes);

Alternatively, for config/routes/index.js, instead of adding the route files (e.g. cart, user) manually, you can load them dynamically:

const fs = require('fs');

let routes = [];

fs.readdirSync(__dirname)
  .filter(file => file != 'index.js')
  .forEach(file => {
    routes = routes.concat(require(`./${file}`))
  });

module.exports = routes;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)