吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1316|回复: 2
收起左侧

[其他原创] 【node后端】koa洋葱模型源码简析+极简复现——简单的递归

  [复制链接]
hans7 发表于 2023-2-2 02:56
本帖最后由 hans7 于 2023-2-2 03:05 编辑

引言

koa里的中间件就是一个函数而已。比如:

app.use(async (ctx, next) => {
  console.log(3);
  ctx.body = 'hello world';
  await next();
  console.log(4);
});

洋葱模型:

const Koa = require('koa');

const app = new Koa();

app.use(async (ctx, next) => {
  console.log(1);
  await next();
  console.log(5);
});
app.use(async (ctx, next) => {
  console.log(2);
  await next();
  console.log(4);
});
app.use(async (ctx, next) => {
  console.log(3);
  ctx.body = 'hello world';
});

app.listen(3001);

执行node index.js,请求3001端口,输出是1~5。

作者:hans774882968以及hans774882968以及hans774882968

本文CSDN:https://blog.csdn.net/hans774882968/article/details/128843088

本文juejin:https://juejin.cn/post/7195249847044145208/
本文52pojie:https://www.52pojie.cn/thread-1740931-1-1.html

源码分析

use函数是定义中间件的入口,传送门

  use (fn) {
    if (typeof fn !== 'function') throw new TypeError('middleware must be a function!')
    debug('use %s', fn._name || fn.name || '-')
    this.middleware.push(fn)
    return this
  }

只是维护了一个middleware数组。

接下来看看调用listen的时候做什么。传送门

  listen (...args) {
    debug('listen')
    const server = http.createServer(this.callback())
    return server.listen(...args)
  }

调用了callback

  callback () {
    const fn = this.compose(this.middleware)

    if (!this.listenerCount('error')) this.on('error', this.onerror)

    const handleRequest = (req, res) => {
      const ctx = this.createContext(req, res)
      return this.handleRequest(ctx, fn)
    }

    return handleRequest
  }

那么需要看compose。我们找到koa-compose的源码,传送门

function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  /**
   * home.php?mod=space&uid=952169 {Object} context
   * home.php?mod=space&uid=155549 {Promise}
   * home.php?mod=space&uid=798433 public
   */

  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}

非常之短。看来node后端和前端一样是🐔⌨️🍚……

经过简单的几步追踪可以看到,中间件那些函数的执行位置就在compose定义的dispatch被执行时。compose返回的function会传给handleRequest,那么我们再看看handleRequest

  /**
   * Handle request in callback.
   *
   * @api private
   */

  handleRequest (ctx, fnMiddleware) {
    const res = ctx.res
    res.statusCode = 404
    const onerror = err => ctx.onerror(err)
    const handleResponse = () => respond(ctx)
    onFinished(res, onerror)
    return fnMiddleware(ctx).then(handleResponse).catch(onerror)
  }

所以中间件是在请求处理的时候执行的,调用fnMiddleware就是调用了compose返回的function,也就调用了dispatch。但是中间件最终由dispatch函数调用,所以要搞清楚洋葱模型的实现,还是要看dispatch函数。

  1. dispatch(0)表示第一个中间件即将执行,fn(context, dispatch.bind(null, i + 1))这句话表示某个中间件正式执行。
  2. 某个中间件调用next就是调用了dispatch.bind(null, i + 1),这样就产生了递归,下一个中间件即将开始执行。最后一个中间件结束后就会回到上一个中间件的next结束之后的位置。
  3. fnMiddleware(ctx)执行完,所有中间件都已经执行完。而中间件执行完,请求已经执行完,之后handleRequest还会做一些对返回值的处理,respond函数传送门
  4. index记录的是执行过的最靠后的中间件的下标。而dispatch的参数i是当前中间件的下标。如果i <= index则表明next在某个函数(中间件)执行了2次。这个i参数的引入就是为了检测某个函数(中间件)执行2次next的非法情况。
  5. handleRequest调用fnMiddleware的情况来看,next参数是undefined(可在node_modules里自己加一个console.log验证),所以if (i === middleware.length) fn = next的作用,就是允许在最后一个中间件调用next函数。

koa洋葱模型简化版实现

下面的代码为了简便,假设在listen时立刻处理请求,不考虑异常处理等额外问题。扔浏览器控制台即可快速运行验证。

function compose(middleware) {
  return (ctx) => {
    function dispatch(i) {
      if (i <= index) throw new Error('next() called multiple times');
      index = i;
      if (i >= middleware.length) return;
      const fn = middleware[i];
      return fn(ctx, () => dispatch(i + 1));
    }
    let index = -1;
    return dispatch(0);
  };
}
const app = {
  middleware: [],
  use(fn) {
    if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
    return this.middleware.push(fn);
  },
  handleRequest(fnMiddleware) {
    console.log('handleRequest');
    const ctx = {};
    fnMiddleware(ctx);
  },
  listen() {
    const fnMiddleware = compose(this.middleware);
    this.handleRequest(fnMiddleware);
  },
};
app.use(async (ctx, next) => {
  console.log(1);
  await next();
  console.log(6, ctx.body);
});
app.use(async (ctx, next) => {
  console.log(2);
  await next();
  console.log(5, ctx.body);
  ctx.body += ' acmer';
});
app.use(async (ctx, next) => {
  console.log(3);
  ctx.body = 'hello world';
  await next();
  console.log(4);
});

app.listen(3000);

参考资料

  1. https://juejin.cn/post/6854573208348295182

免费评分

参与人数 5吾爱币 +11 热心值 +5 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
笙若 + 1 + 1 谢谢@Thanks!
E式丶男孩 + 1 + 1 写的太好了
daoye9988 + 1 + 1 热心回复!
为之奈何? + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

鹤舞九月天 发表于 2023-2-2 07:06
学习一下,谢谢分享
野男人 发表于 2023-2-3 13:51
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-21 16:19

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表