egg icon indicating copy to clipboard operation
egg copied to clipboard

大型项目router写法的疑问?

Open kylehuangfff opened this issue 8 years ago • 7 comments

背景: 最近公司一个大型项目,准备基于eggjs做前后端分离,项目包含超过20多个模块,每个模块下面还有数十个子模块,总的接口数量超过500个。

问题: 根据官方文档,以及像CNode 的egg版,都把需要用到的路由地址,写在router里面,那么如果有几百个url地址,岂不是要注册几百个路由呢? 更严重的是,极端情况下,某些用户请求,需要经过几百次路径检测,才能匹配到相应的控制器。

我的解决方法: 1、router里面只有类似这样一行路由 router.get(/^/(.*?)$/, controller.base.entry);

2、创建一个BaseController,继承egg Controller。在BaseController里再做路径处理,进行请求分发。

3、BaseController以外的其他控制器,不继承egg Controller。仅export数个方法。

// app/controller/home.js module.exports = { async index() { } }

当访问路径为 '/home/index'时,由BaseController主动进行调用,controller.home.index.call(this),传入BaseController所持有的this对象。

疑问: 1、这样的写法有没有潜在的问题? 2、官方是否有更好的解决方案?

谢谢!

kylehuangfff avatar Apr 13 '18 09:04 kylehuangfff

Translation of this issue:


Question about large project router writing?

background: Recently, a large-scale project of the company is preparing to do front-end and back-end separation based on eggjs. The project contains more than 20 modules, each module has dozens of sub-modules, and the total number of interfaces exceeds 500.

problem: According to the official documentation, and the egg version of the CNode, all the routing addresses that need to be used are written in the router. So if there are hundreds of url addresses, wouldn't it be necessary to register hundreds of routes? What's more, in extreme cases, some user requests need to go through hundreds of path detections to match the corresponding controller.

My solution: 1, router inside only similar to such a route Router.get(/^/(.*?)$/, controller.base.entry);

2, create a BaseController, inherited egg Controller. In the BaseController do path processing, request distribution.

  1. Controllers other than BaseController do not inherit the egg controller. Only export a few methods.

// app/controller/home.js Module.exports = {     Async index() {     } }

When the access path is '/home/index', BaseController takes the initiative to call it and controller.home.index.call(this) passes in the this object that BaseController holds.

doubt:

  1. Is there any potential problem with this writing?
  2. Does the government have a better solution?

Thank you!

egg-bot avatar Apr 13 '18 09:04 egg-bot

创建一个BaseController,继承egg Controller。在BaseController里再做路径处理,进行请求分发。

你确定不是同样自己实现了一个 router?现在 egg 的 router 性能足够了,不用纠结。

dead-horse avatar Apr 13 '18 09:04 dead-horse

呃,这么做是希望做路由嵌套分发吗?

TyrSnow avatar Apr 13 '18 09:04 TyrSnow

  1. 你这种写法,不就是重新实现了一个 koa-router,意义何在?
  2. 如果你只是解决一大堆东西写在一个文件,那就自己分文件 require 咯,或者用 egg-router-plus

atian25 avatar Apr 13 '18 09:04 atian25

@dead-horse @atian25 初衷是避免在上层框架注册大量路由。如果egg能内置路径自动匹配控制器的特性就好了,谢谢二位~

kylehuangfff avatar Apr 13 '18 10:04 kylehuangfff

路径自动匹配控制器 这个特性并不是通用特性,只适合在插件里面做,根据你们自己的需求做就好了,参考 egg-router-plus

atian25 avatar Apr 13 '18 10:04 atian25

@atian25 明白了,谢谢指点~

kylehuangfff avatar Apr 13 '18 10:04 kylehuangfff