飞雪连天射白鹿,笑书神侠倚碧鸳

0%

koa2简易实现

核心功能洋葱模型

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
}
}
// 启动服务
// const app = new Application()
// app.use((req,res)=>{res.end('- -')})
// app.listen(3000)

构建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
// 此时app.use的回调函数是原生的req,res,而koa中是一个Context对象
const http = require('http');
class Application{
constructor(){
this.middleware=null
}
listen(...args){
const server = http.createServer((req,res)=>{
// 创建Context对象
const ctx = new Context(req,res);
// 处理 app.use
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;
}
}
// 启动服务
// const app = new Application()
// app.use(ctx=>{ctx.body('- -')})
// app.listen(3000)

中间件

手机中间件回调函数数组,并使用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)
}
}
// 使用
// const app = new Application()
// app.use(async(ctx)=>{
// ctx.body('- -')
// await next()
// })
// app.use(async (ctxnext)=>{
// ctx.body('- -')
// await next()
// })
// app.use(async (ctx,next)=>{
// ctx.body='富士山
// await next()
// })
// app.listen(3000)
听说,打赏我的人最后都找到了真爱
↘ 此处应有打赏 ↙
// 用户脚本