洋葱模型

下面两张图是网上找的,很清晰的表明了一个请求是如何经过中间件最后生成响应的,这种模式中开发和使用中间件都是非常方便的 [20190801] 手写 koa - 图2

image.png

来看一个koa2的demo:

  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const PORT = 3000;
  4. // #1
  5. app.use(async (ctx, next)=>{
  6. console.log(1)
  7. await next();
  8. console.log(1)
  9. });
  10. // #2
  11. app.use(async (ctx, next) => {
  12. console.log(2)
  13. await next();
  14. console.log(2)
  15. })
  16. app.use(async (ctx, next) => {
  17. console.log(3)
  18. })
  19. app.listen(PORT);
  20. console.log(`http://localhost:${PORT}`);

访问http://localhost:3000,控制台打印;
怎么样,是不是有一点点感觉了。当程序运行到await next()的时候就会暂停当前程序,进入下一个中间件,处理完之后才会仔回过头来继续处理。也就是说,当一个请求进入,#1会被第一个和最后一个经过,#2则是被第二和倒数第二个经过,依次类推。

一个简单的 http 服务

使用 node 提供的 http 模块,可以很容易的实现一个基本的 http 服务器,新建一个 application.js 文件,内容如下:

  1. const http = require('http');
  2. const server = http.createServer((req, res) => {
  3. res.end("hello world");
  4. });
  5. server.listen(8080, ()=> {
  6. console.log('Server is running at 8080.')
  7. });

之后通过 node 来启动这个脚本,打开浏览器 输入地址 localhost:8080,即可访问。

改造成服务类

接下来在这个基础上改造一下,把 server 封装成一个对象。

  1. // application.js
  2. const http = require('http');
  3. class Application {
  4. constructor(){}
  5. use(cb){
  6. this.callback = cb;
  7. }
  8. listen(...args){
  9. const server = http.createServer((req, res) => {
  10. this.callback(req, res);
  11. });
  12. server.listen(...args)
  13. }
  14. }
  15. module.exports = Application;

新建 server.js ,测试代码如下:

  1. //server.js
  2. const Koa = require('./application');
  3. const app = new Koa();
  4. app.use((req, res) => {
  5. res.end("hello world");
  6. });
  7. app.listen(8080, ()=> {
  8. console.log('Server is running at 8080.')
  9. });

封装上下文对象

为了实现类似 Koa 那种 ctx.xxx 这样的方式,先来新建3个文件:request.js,response.js,context.js 。

  1. // request.js
  2. const request = {
  3. get url() {
  4. return this.req.url;
  5. }
  6. };
  7. module.exports = request;
  1. // response.js
  2. const response = {
  3. get body(){
  4. return this._body;
  5. },
  6. set body(val){
  7. this._body = val;
  8. }
  9. };
  10. module.exports = response;
  1. // context.js
  2. const context = {
  3. get url(){
  4. return this.request.url;
  5. },
  6. get body(){
  7. return this.response.body;
  8. },
  9. set body(val){
  10. this.response.body = val;
  11. }
  12. };
  13. module.exports = context;

整合上下文对象到服务类

可能看到上面3个对象,会有点迷糊的感觉,下面就把这3个对象添加到 Application 类中:

  1. const http = require('http');
  2. const request = require('./request');
  3. const response = require('./response');
  4. const context = require('./context');
  5. class Application {
  6. constructor(){
  7. this.context = context;
  8. this.request = request;
  9. this.response = response;
  10. }
  11. use(cb){
  12. this.callback = cb;
  13. }
  14. createCtx(req, res){
  15. const ctx = Object.create(this.context);
  16. ctx.request = Object.create(this.request);
  17. ctx.response = Object.create(this.response);
  18. ctx.req = ctx.request.req = req;
  19. ctx.res = ctx.response.res = res;
  20. return ctx;
  21. }
  22. listen(...args){
  23. const server = http.createServer(async (req, res) => {
  24. const ctx = this.createCtx(req, res);
  25. await this.callback(ctx);
  26. ctx.res.end(ctx.body);
  27. });
  28. server.listen(...args)
  29. }
  30. }
  31. module.exports = Application;

修改 server.js 文件,再次测试:

  1. const Koa = require('./application');
  2. const app = new Koa();
  3. app.use(async (ctx)=> {
  4. ctx.body = ctx.url;
  5. });
  6. app.listen(8080, ()=> {
  7. console.log('Server is running at 8080.')
  8. });

串联中间件

到此为止,咱们写的 Koa 只能使用一个中间件,而且还不涉及到异步,下面咱们就一起来看看 Koa 中最核心的 compose 函数,是如何把各个中间件串联起来的。

为了更容易的理解,先来写一个同步版本的,依次执行 fn1, fn2:

  1. // compose.js
  2. const fn1 = x => Math.pow(x, 2);
  3. const fn2 = x => 2 * x;
  4. function compose (middlewares){
  5. return (x) => {
  6. let ret = middlewares[0](x);
  7. for(let i=1; i<middlewares.length; i++){
  8. ret = middlewares[i](ret);
  9. }
  10. return ret;
  11. }
  12. }
  13. const fn = compose([fn1, fn2]);
  14. console.log(fn(3));

上面代码可以直接在浏览器中测试结果。

那么如果 fn1 fn2 中如果有异步操作,应该如何处理呢,实际上只需要使用 Promise 改造一下 compose 的逻辑即可。

  1. // compose.js
  2. // 首先实现一个测试用休眠函数:
  3. const sleep = (duration = 2000) => new Promise((resolve) => {
  4. setTimeout(resolve, duration);
  5. });
  6. // 其次准备3个测试用异步函数,最终效果是实现一个洋葱模型:
  7. const fn1 = async(next)=> {
  8. console.log('fn1 start 休眠2秒');
  9. await sleep();
  10. await next();
  11. console.log('fn1 over')
  12. }
  13. const fn2 = async (next) => {
  14. console.log('fn2 start 休眠3秒')
  15. await sleep(3000);
  16. await next();
  17. console.log('fn2 duration');
  18. await sleep(1000);
  19. console.log('fn2 over');
  20. }
  21. const fn3 = async (next)=> {
  22. console.log('fn3 start');
  23. await sleep();
  24. console.log('fn3 over');
  25. }

执行的顺序为 fn1 > fn2 > fn3 > fn2 > fn1
最后就是主角 componse

  1. function compose(middlewares){
  2. return (context) => {
  3. return dispatch(0);
  4. function dispatch(i){
  5. const fn = middlewares[i];
  6. if(!fn) return Promise.resolve()
  7. return Promise.resolve(fn(function next(){
  8. console.log('exec next')
  9. return dispatch(i+1);
  10. }))
  11. }
  12. }
  13. }

测试用例:

  1. const fn = compose([fn1, fn2, fn3]);
  2. fn();

整合compose到Server

废话不说,直接上代码:

  1. // application.js
  2. const http = require('http');
  3. const request = require('./request');
  4. const response = require('./response');
  5. const context = require('./context');
  6. class Application {
  7. constructor(){
  8. this.context = context;
  9. this.request = request;
  10. this.response = response;
  11. this.middlewares = [];
  12. }
  13. use(middleware){
  14. this.middlewares.push(middleware)
  15. return this;
  16. }
  17. createCtx(req, res){
  18. const ctx = Object.create(this.context);
  19. ctx.request = Object.create(this.request);
  20. ctx.response = Object.create(this.response);
  21. ctx.req = ctx.request.req = req;
  22. ctx.res = ctx.response.res = res;
  23. return ctx;
  24. }
  25. compose(middlewares){
  26. return ctx => {
  27. return dispatch(0);
  28. function dispatch(index) {
  29. const fn = middlewares[index++];
  30. if(!fn || typeof fn !== 'function'){
  31. return Promise.resolve()
  32. }
  33. return Promise.resolve(fn(ctx, next));
  34. function next(){
  35. return dispatch(index);
  36. }
  37. }
  38. }
  39. }
  40. listen(...args){
  41. const server = http.createServer(async (req, res) => {
  42. const ctx = this.createCtx(req, res);
  43. const fn = this.compose(this.middlewares);
  44. await fn(ctx);
  45. ctx.res.end(ctx.body);
  46. });
  47. server.listen(...args)
  48. }
  49. }
  50. module.exports = Application;

下面可以测试一下了~

  1. // server.js
  2. const Koa = require('./application');
  3. const app = new Koa();
  4. const sleep = (time) => new Promise((resolve, reject) => {
  5. setTimeout(resolve, time || 2000);
  6. })
  7. app.use(async (ctx, next)=> {
  8. ctx.body = ctx.url;
  9. await sleep();
  10. await next();
  11. ctx.body += '111111'
  12. });
  13. app.use(async (ctx, next)=> {
  14. ctx.body += '22222'
  15. await sleep();
  16. await next();
  17. });
  18. app.use(async(ctx, next) => {
  19. ctx.body +='33333';
  20. })
  21. app.listen(8080, ()=> {
  22. console.log('Server is running at 8080.')
  23. });

结果:

image.png
improve: reduce stack trace by removing useless function call (#95)

  1. return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));