核心功能洋葱模型
1 2 3
| Application http server 基本服务器框架 Context 上下文 服务器框架基本数据结构的封装,解析响应http请求 Middleware 中间件,洋葱模型机制
|
启动一个简单的http服务
1 2 3 4 5
| const http = require('http'); const server = http.createServer((req,res)=>{ res.end('- -') }) server.listen(3000)
|
app.listen处理请求和端口监听
app.use处理中间件和请求
myKoa
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const http = require('http'); class Application{ constructor(){ this.middleware=null } listen(...args){ const server = http.createServer(this.middleware); server.listen(...args); } use(middleware){ this.middleware = middleware } }
|
构建Context
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const http = require('http'); class Application{ constructor(){ this.middleware=null } listen(...args){ const server = http.createServer((req,res)=>{ const ctx = new Context(req,res); this.middleware(ctx); ctx.res.end(ctx.body); }); server.listen(...args); } use(middleware){ this.middleware = middleware } } class Context{ constructor(req,res){ this.req=req; this.res=res; } }
|
中间件
手机中间件回调函数数组,并使用compose串联起来
对所有中间件函数通过compose函数来达到抽象效果
1 2 3 4
| const fn = compose(this.middlewares); await fn(ctx);
await compose(this.middlwares,ctx);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const http = require('http'); class Application{ constructor(){ this.middlewares=[] } listen(...args){ const server = http.createServer(async (req,res)=>{ const ctx = new Context(req,res); const fn = compose(this.middlewares); await fn(ctx);
ctx.res.end(ctx.body); }); server.listen(...args); } use(middleware){ this.middlewares.push(middleware) } } class Context{ constructo(req,res){ this.req=req; this.res=res; } }
|
第一个中间件将会执行。后续每个会通过next执行
使用递归完成中间件的改造,实现洋葱模型
1 2 3 4 5 6
| const dispatch=(i)=>{ return middlewares[i](ctx,()=>{ dispatch(i+1) }) } dispatch(0)
|
1 2 3 4 5 6 7 8 9 10
| const dispatch=(i)=>{ const middleware = middlewares[i]; if(i === middlewares.length){ return; } return middleware(ctx,()=>{ dispatch(i+1) }) } dispatch(0)
|
最后的compose
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function compose(middlewares){ return ctx=>{ const dispatch=(i)=>{ const middleware = middlewares[i]; if(i === middlewares.length){ return; } return middleware(ctx,()=>{ dispatch(i+1) }) } return dispatch(0) } }
|