How to store routes in separate files when using Hapi?

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

    or you can use a index file to load all the routes in the directory

    index.js

    /**
     * Module dependencies.
     */
    const fs = require('fs');
    const path = require('path');
    const basename  = path.basename(__filename);
    
    const routes = fs.readdirSync(__dirname)
    .filter((file) => {
        return (file.indexOf('.') !== 0) && (file !== basename);
    })
    .map((file) => {
        return require(path.join(__dirname, file));
    });
    
    module.exports = routes;
    

    other files in the same directory like:

    module.exports =  [
        {
            method: 'POST',
            path:  '/api/user',
            config: {
    
            }
        },
        {
            method: 'PUT',
            path:  'api/user/{userId}',
            config: {
    
            }
        }
    ];
    

    and than in your root/index

    const Routes = require('./src/routes');
    /**
    * Add all the routes
    */
    for (var route in Routes) {
        server.route(Routes[route]);
    }
    

提交回复
热议问题