How to store routes in separate files when using Hapi?

前端 未结 7 2019
醉话见心
醉话见心 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 01:59

    You should try Glue plugin: https://github.com/hapijs/glue. It allows you to modularize your application. You can place your routes in separate subdirectories and then include them as Hapi.js plugins. You can also include other plugins (Inert, Vision, Good) with Glue as well as configure your application with a manifest object (or json file).

    Quick exapmple:

    server.js:

    var Hapi = require('hapi');
    var Glue = require('glue');
    
    var manifest = {
        connections: [{
            port: 8080
        }],
        plugins: [
            { inert: [{}] },
            { vision: [{}] },
            { './index': null },
            {
                './api': [{
                    routes: {
                        prefix: '/api/v1'
                    }
                }]
            }
        ]
    };
    
    
    var options = {
        relativeTo: __dirname + '/modules'
    };
    
    Glue.compose(manifest, options, function (err, server) {
        server.start(function(err) {
            console.log('Server running at: %s://%s:%s', server.info.protocol, server.info.address, server.info.port);
        });
    });
    

    ./modules/index/index.js:

    exports.register = function(server, options, next) {
        server.route({
            method: 'GET',
            path: '/',
            handler: require('./home')
        });
    });
    
    exports.register.attributes = {
        pkg: require('./package.json')
    };
    

    ./modules/index/package.json:

    {
        "name": "IndexRoute",
        "version": "1.0.0"
    }
    

    ./modules/index/home.js:

    exports.register = function(req, reply) {
        reply.view('home', { title: 'Awesome' });
    });
    

    Have a look at this wonderful article by Dave Stevens for more details and examples.

提交回复
热议问题