How to store routes in separate files when using Hapi?

前端 未结 7 2016
醉话见心
醉话见心 2021-01-30 01:49

All of the Hapi examples (and similar in Express) shows routes are defined in the starting file:

var Hapi = require(\'hapi\');

var server = new Hapi.Server();
s         


        
7条回答
  •  情深已故
    2021-01-30 02:08

    Interesting to see so many different solutions, here is another one.

    Globbing to the rescue

    For my latest project I settled on globbing for files with a particular name pattern and then requiring them into the server one by one.

    Import routes after having created the server object

    // Construct and setup the server object.
    // ...
    
    // Require routes.
    Glob.sync('**/*route*.js', { cwd: __dirname }).forEach(function (ith) {
        const route = require('./' + ith);
        if (route.hasOwnProperty('method') && route.hasOwnProperty('path')) {
            console.log('Adding route:', route.method, route.path);
            server.route(route);
        }
    });
    
    // Start the server.
    // ...
    

    The glob pattern **/*route*.js will find all files within and below the specified current working directory with a name that contains the word route and ends with the suffix .js.

    File structure

    With the help of globbing we have a loose coupling between the server object and its routes. Just add new route files and they will be included the next time you restart your server.

    I like to structure the route files according to their path and naming them with their HTTP-method, like so:

    server.js
    routes/
        users/
            get-route.js
            patch-route.js
            put-route.js
        articles/
            get-route.js
            patch-route.js
            put-route.js
    

    Example route file routes/users/get-route.js

    module.exports = {
        method: 'GET',
        path: '/users',
        config: {
            description: 'Fetch users',
            // ...
        },
        handler: function (request, reply) {
            // ...
        }
    };
    

    Final thoughts

    Globbing and iterating over files is not a particularly fast process, hence a caching layer may be worth investigating in production builds depending on your circumstances.

提交回复
热议问题