7

请教后端业务逻辑代码如何分离

 2 years ago
source link: https://www.v2ex.com/t/816854
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Node.js

请教后端业务逻辑代码如何分离

  px920906 · 1 天前 · 859 次点击

node+koa ,有这样一个接口:

router.post(
  '/order',
  {...}, 
  async ctx => {
    const { body } = ctx.request
    // 一些需要查询数据库的参数验证逻辑,比如:
    const item = await Item.findOne({ where: { id: body.id } })
    if (!item) {
      throw Error('item not existing')
    }
    // 后续逻辑
    const result = await createOrder(body)
    ctx.body = result.id
  }
)

createOrder这个函数因为其他接口 /逻辑也会用到所以单独抽出来了,于是产生个问题: 函数内部也有用到查询Item的地方,那这样的话,/order这一个接口得查询Item两次。例子是查一个,查列表的情况岂不是更浪费。

抽象出来大概是:如何避免 通用业务逻辑 与 调用它的 route 之间重复相同数据库查询操作?

求赐教!谢谢!

第 1 条附言  ·  6 小时 58 分钟前

总结下前 6 楼的方案:
1. item 作为可选参数传到函数里,但感觉不太优雅
2. 查询一次之后把 item 缓存到全局变量里供后续使用。但可能会有时效性的问题,比如在验证之后、执行 createOrder 之前,另一个接口调用导致 item 发生了更新 /删除。其实方案一也有这个问题。
3. 对 Item.create 进行二次封装,加入验证逻辑。这样的话又有另一个麻烦的点:
当函数内部创建 item 时验证参数(注意是 createOrder 函数接收的参数)失败,抛出一个错误,里面包含对应参数(形参的名称,以字符串形式给出)和错误原因,那 route 捕获到这个错误之后要抛出客户端错误,如何将函数参数和 request 里的参数对应?因为这两个不一定是对称的,比如传进接口的是 item['id'],但传给 createOrder 的形参是 itemId 。

不知道还有没有更好的办法。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK