我有一个“ Controller ”中间件(连接到 koa-router)。
我想知道组织“内部”应用程序逻辑的最佳方法是什么(除了我的 Controller ,连接到 koa-router 的中间件功能 router.post('/',创建Ctrl)
)。
第一种情况:“一切都是中间件”。我的 Controller 只是组成了逐步从初始请求对象到非常适合的响应对象所需的一组中间件函数。 (我通过 ctx.state 读取并传递下一个中间件所需的参数)。
import * as view from './views' import * as repo from './repository' import * as response from '../../services/response' import { sign } from '../../services/jwt' import compose from 'koa-compose' const createCtrl = compose([ repo.create(), sign(), view.sessionUser(), response.success(201) ])
第二种情况:应用逻辑与 Koa 完全“解耦”。 Controller 将是一个调用非中间件函数的 koa 中间件,如下所示:
import * as view from './views' import * as repo from './repository' import * as response from '../../services/response' import { sign } from '../../services/jwt' const createCtrl = async function (ctx) { try { const entity = await repo.create() const token = await sign(entity.id) const dto = view.sessionUser(token, entity) const response = response.success(201) response(ctx, dto) // <- this is also a middleware } catch(err) { ctx.throw(500, 'my not very well handled error') } }
将 Controller 视为中间件功能的组合是个好主意吗?或者这是对中间件功能的误用?
最佳答案
最好的方法是将逻辑与 Controller 分开。通过这种分离,您可以在应用程序的其他部分重用相同的逻辑,并且测试起来更加容易。
请检查此存储库:https://github.com/Talento90/typescript-node
我有一个服务器文件夹,其中放置了所有服务器基础设施,例如 Controller 和路由(两者都是分开的),然后将我的管理器传递给服务器。管理器包含应用程序逻辑并传递到服务器。
总结一下:应用程序逻辑绝不能依赖于基础设施(在本例中为 HTTP 服务器)。
关于javascript - koa2:如何组织路由器 Controller 逻辑(中间件与非中间件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331296/