使用Hapi时如何将路由存储在单独的文件中? [英] How to store routes in separate files when using Hapi?

查看:84
本文介绍了使用Hapi时如何将路由存储在单独的文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有Hapi示例(以及Express中的类似示例)都显示了在起始文件中定义了路由:

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();
server.connection({ port: 8000 });

server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    reply('Hello, world!');
  }
});

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
  }
});

server.start(function () {
  console.log('Server running at:', server.info.uri);
});

但是,不难想象,当用大量不同的路线实现生产应用程序时,此文件可以增长到多大.因此,我想分解路由,将它们分组并存储在单独的文件中,例如UserRoutes.js,CartRoutes.js,然后将它们附加到主文件中(添加到服务器对象).您如何建议将其分开然后添加?

However, it's not hard to image how large this file can grow when implementing production application with a ton of different routes. Therefore I would like to break down routes, group them and store in separate files, like UserRoutes.js, CartRoutes.js and then attach them in the main file (add to server object). How would you suggest to separate that and then add?

推荐答案

您可以为用户路由(config/routes/user.js)创建一个单独的文件:

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

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

与购物车类似.然后在config/routes(config/routes/index.js)中创建一个索引文件:

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);

然后您可以将该索引文件加载到主文件中,并调用server.route():

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

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

...

server.route(routes);

或者,对于config/routes/index.js,您可以动态加载它们,而不是手动添加路由文件(例如,cartuser):

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;

这篇关于使用Hapi时如何将路由存储在单独的文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆