洋葱模型
下面两张图是网上找的,很清晰的表明了一个请求是如何经过中间件最后生成响应的,这种模式中开发和使用中间件都是非常方便的
![[20190801] 手写 koa - 图2](/uploads/projects/ericlee@fontend/bd057881438654512a7ff91788c89850.png)
来看一个koa2的demo:
const Koa = require('koa');const app = new Koa();const PORT = 3000;// #1app.use(async (ctx, next)=>{console.log(1)await next();console.log(1)});// #2app.use(async (ctx, next) => {console.log(2)await next();console.log(2)})app.use(async (ctx, next) => {console.log(3)})app.listen(PORT);console.log(`http://localhost:${PORT}`);
访问http://localhost:3000,控制台打印;
怎么样,是不是有一点点感觉了。当程序运行到await next()的时候就会暂停当前程序,进入下一个中间件,处理完之后才会仔回过头来继续处理。也就是说,当一个请求进入,#1会被第一个和最后一个经过,#2则是被第二和倒数第二个经过,依次类推。
一个简单的 http 服务
使用 node 提供的 http 模块,可以很容易的实现一个基本的 http 服务器,新建一个 application.js 文件,内容如下:
const http = require('http');const server = http.createServer((req, res) => {res.end("hello world");});server.listen(8080, ()=> {console.log('Server is running at 8080.')});
之后通过 node 来启动这个脚本,打开浏览器 输入地址 localhost:8080,即可访问。
改造成服务类
接下来在这个基础上改造一下,把 server 封装成一个对象。
// application.jsconst http = require('http');class Application {constructor(){}use(cb){this.callback = cb;}listen(...args){const server = http.createServer((req, res) => {this.callback(req, res);});server.listen(...args)}}module.exports = Application;
新建 server.js ,测试代码如下:
//server.jsconst Koa = require('./application');const app = new Koa();app.use((req, res) => {res.end("hello world");});app.listen(8080, ()=> {console.log('Server is running at 8080.')});
封装上下文对象
为了实现类似 Koa 那种 ctx.xxx 这样的方式,先来新建3个文件:request.js,response.js,context.js 。
// request.jsconst request = {get url() {return this.req.url;}};module.exports = request;
// response.jsconst response = {get body(){return this._body;},set body(val){this._body = val;}};module.exports = response;
// context.jsconst context = {get url(){return this.request.url;},get body(){return this.response.body;},set body(val){this.response.body = val;}};module.exports = context;
整合上下文对象到服务类
可能看到上面3个对象,会有点迷糊的感觉,下面就把这3个对象添加到 Application 类中:
const http = require('http');const request = require('./request');const response = require('./response');const context = require('./context');class Application {constructor(){this.context = context;this.request = request;this.response = response;}use(cb){this.callback = cb;}createCtx(req, res){const ctx = Object.create(this.context);ctx.request = Object.create(this.request);ctx.response = Object.create(this.response);ctx.req = ctx.request.req = req;ctx.res = ctx.response.res = res;return ctx;}listen(...args){const server = http.createServer(async (req, res) => {const ctx = this.createCtx(req, res);await this.callback(ctx);ctx.res.end(ctx.body);});server.listen(...args)}}module.exports = Application;
修改 server.js 文件,再次测试:
const Koa = require('./application');const app = new Koa();app.use(async (ctx)=> {ctx.body = ctx.url;});app.listen(8080, ()=> {console.log('Server is running at 8080.')});
串联中间件
到此为止,咱们写的 Koa 只能使用一个中间件,而且还不涉及到异步,下面咱们就一起来看看 Koa 中最核心的 compose 函数,是如何把各个中间件串联起来的。
为了更容易的理解,先来写一个同步版本的,依次执行 fn1, fn2:
// compose.jsconst fn1 = x => Math.pow(x, 2);const fn2 = x => 2 * x;function compose (middlewares){return (x) => {let ret = middlewares[0](x);for(let i=1; i<middlewares.length; i++){ret = middlewares[i](ret);}return ret;}}const fn = compose([fn1, fn2]);console.log(fn(3));
上面代码可以直接在浏览器中测试结果。
那么如果 fn1 fn2 中如果有异步操作,应该如何处理呢,实际上只需要使用 Promise 改造一下 compose 的逻辑即可。
// compose.js// 首先实现一个测试用休眠函数:const sleep = (duration = 2000) => new Promise((resolve) => {setTimeout(resolve, duration);});// 其次准备3个测试用异步函数,最终效果是实现一个洋葱模型:const fn1 = async(next)=> {console.log('fn1 start 休眠2秒');await sleep();await next();console.log('fn1 over')}const fn2 = async (next) => {console.log('fn2 start 休眠3秒')await sleep(3000);await next();console.log('fn2 duration');await sleep(1000);console.log('fn2 over');}const fn3 = async (next)=> {console.log('fn3 start');await sleep();console.log('fn3 over');}
执行的顺序为 fn1 > fn2 > fn3 > fn2 > fn1
最后就是主角 componse
function compose(middlewares){return (context) => {return dispatch(0);function dispatch(i){const fn = middlewares[i];if(!fn) return Promise.resolve()return Promise.resolve(fn(function next(){console.log('exec next')return dispatch(i+1);}))}}}
测试用例:
const fn = compose([fn1, fn2, fn3]);fn();
整合compose到Server
废话不说,直接上代码:
// application.jsconst http = require('http');const request = require('./request');const response = require('./response');const context = require('./context');class Application {constructor(){this.context = context;this.request = request;this.response = response;this.middlewares = [];}use(middleware){this.middlewares.push(middleware)return this;}createCtx(req, res){const ctx = Object.create(this.context);ctx.request = Object.create(this.request);ctx.response = Object.create(this.response);ctx.req = ctx.request.req = req;ctx.res = ctx.response.res = res;return ctx;}compose(middlewares){return ctx => {return dispatch(0);function dispatch(index) {const fn = middlewares[index++];if(!fn || typeof fn !== 'function'){return Promise.resolve()}return Promise.resolve(fn(ctx, next));function next(){return dispatch(index);}}}}listen(...args){const server = http.createServer(async (req, res) => {const ctx = this.createCtx(req, res);const fn = this.compose(this.middlewares);await fn(ctx);ctx.res.end(ctx.body);});server.listen(...args)}}module.exports = Application;
下面可以测试一下了~
// server.jsconst Koa = require('./application');const app = new Koa();const sleep = (time) => new Promise((resolve, reject) => {setTimeout(resolve, time || 2000);})app.use(async (ctx, next)=> {ctx.body = ctx.url;await sleep();await next();ctx.body += '111111'});app.use(async (ctx, next)=> {ctx.body += '22222'await sleep();await next();});app.use(async(ctx, next) => {ctx.body +='33333';})app.listen(8080, ()=> {console.log('Server is running at 8080.')});
结果:

improve: reduce stack trace by removing useless function call (#95)
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));

