How to store routes in separate files when using Hapi?

前端 未结 7 1948
醉话见心
醉话见心 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:19

    You can use require-hapiroutes to do some of the organization and loading for you. (I am the author so I am a little biased, I wrote it to make my life easier in managing routes)

    I am a big fan of require-directory and and wanted a way to manage my routes just as easily. This lets you mix and match routes in your modules and modules in directories with routes.

    You can then do something like this...

    var routes = require('./routes');
    server.route(routes.routes);
    

    Then in your directory you could have a route file like...

    module.exports = [
    {
      method : 'GET',
      path : '/route1',
      handler : routeHandler1,
      config : {
        description: 'my route description',
        notes: 'Important stuff to know about this route',
        tags : ['app']
      }
    },
    {
      method : 'GET',
      path : '/route2',
      handler : routeHandler2,
      config : {
        description: 'my route description',
        notes: 'Important stuff to know about this route',
        tags : ['app']
      }
    }];
    

    Or, you can mix and match by assigning to a "routes" property on the module

    module.exports.routes = [
    {
      method : 'GET',
      path : '/route1',
      handler : routeHandler1,
      config : {
        description: 'my route description',
        notes: 'Important stuff to know about this route',
        tags : ['app']
      }
    },
    {
      method : 'GET',
      path : '/route2',
      handler : routeHandler2,
      config : {
        description: 'my route description',
        notes: 'Important stuff to know about this route',
        tags : ['app']
      }
    }];
    

    Always, good to have options. There is full documentation on the github or npmjs site for it.

提交回复
热议问题