前言
node.js也是写了两三年的时间了,刚开始学习node的时候,hello world就是创建一个httpserver,后来在工作中也是经历过express、koa1.x、koa2.x以及最近还在研究的结合着typescript的routing-controllers(驱动依然是express与koa)。
用的比较多的还是koa版本,也是对它的洋葱模型比较感兴趣,所以最近抽出时间来阅读其源码,正好近期可能会对一个express项目进行重构,将其重构为koa2.x版本的,所以,阅读其源码对于重构也是一种有效的帮助。
koa是怎么来的
首先需要确定,koa是什么。
任何一个框架的出现都是为了解决问题,而koa则是为了更方便的构建http服务而出现的。
可以简单的理解为一个http服务的中间件框架。
使用http模块创建http服务
相信大家在学习node时,应该都写过类似这样的代码:
const http = require('http')
const serverhandler = (request, response) => {
response.end('hello world') // 返回数据
}
http
.createserver(serverhandler)
.listen(8888, _ => console.log('server run as http://127.0.0.1:8888'))
一个最简单的示例,脚本运行后访问http://127.0.0.1:8888即可看到一个hello world的字符串。
但是这仅仅是一个简单的示例,因为我们不管访问什么地址(甚至修改请求的method),都总是会获取到这个字符串:
> curl http://127.0.0.1:8888 > curl http://127.0.0.1:8888/sub > curl -x post http://127.0.0.1:8888
所以我们可能会在回调中添加逻辑,根据路径、method来返回给用户对应的数据:
const serverhandler = (request, response) => {
// default
let responsedata = '404'
if (request.url === '/') {
if (request.method === 'get') {
responsedata = 'hello world'
} else if (request.method === 'post') {
responsedata = 'hello world with post'
}
} else if (request.url === '/sub') {
responsedata = 'sub page'
}
response.end(responsedata) // 返回数据
}
类似express的实现
但是这样的写法还会带来另一个问题,如果是一个很大的项目,存在n多的接口。
如果都写在这一个handler里边去,未免太过难以维护。
示例只是简单的针对一个变量进行赋值,但是真实的项目不会有这么简单的逻辑存在的。
所以,我们针对handler进行一次抽象,让我们能够方便的管理路径:
class app {
constructor() {
this.handlers = {}
this.get = this.route.bind(this, 'get')
this.post = this.route.bind(this, 'post')
}
route(method, path, handler) {
let pathinfo = (this.handlers[path] = this.handlers[path] || {})
// register handler
pathinfo[method] = handler
}
callback() {
return (request, response) => {
let { url: path, method } = request
this.handlers[path] && this.handlers[path][method]
? this.handlers[path][method](request, response)
: response.end('404')
}
}
}
然后通过实例化一个router对象进行注册对应的路径,最后启动服务:
const app = new app()
app.get('/', function (request, response) {
response.end('hello world')
})
app.post('/', function (request, response) {
response.end('hello world with post')
})
app.get('/sub', function (request, response) {
response.end('sub page')
})
http
.createserver(app.callback())
.listen(8888, _ => console.log('server run as http://127.0.0.1:8888'))
express中的中间件
这样,就实现了一个代码比较整洁的httpserver,但功能上依旧是很简陋的。
如果我们现在有一个需求,要在部分请求的前边添加一些参数的生成,比如一个请求的唯一id。
将代码重复编写在我们的handler中肯定是不可取的。
所以我们要针对route的处理进行优化,使其支持传入多个handler:
route(method, path, ...handler) {
let pathinfo = (this.handlers[path] = this.handlers[path] || {})
// register handler
pathinfo[method] = handler
}
callback() {
return (request, response) => {
let { url: path, method } = request
let handlers = this.handlers[path] && this.handlers[path][method]
if (handlers) {
let context = {}
function next(handlers, index = 0) {
handlers[index] &&
handlers[index].call(context, request, response, () =>
next(handlers, index + 1)
)
}
next(handlers)
} else {
response.end('404')
}
}
}
然后针对上边的路径监听添加其他的handler:
function generatorid(request, response, next) {
this.id = 123
next()
}
app.get('/', generatorid, function(request, response) {
response.end(`hello world ${this.id}`)
})
这样在访问接口时,就可以看到hello world 123的字样了。
这个就可以简单的认为是在express中实现的 中间件。
中间件是express、koa的核心所在,一切依赖都通过中间件来进行加载。
更灵活的中间件方案-洋葱模型
上述方案的确可以让人很方便的使用一些中间件,在流程控制中调用next()来进入下一个环节,整个流程变得很清晰。
但是依然存在一些局限性。
例如如果我们需要进行一些接口的耗时统计,在express有这么几种可以实现的方案:
function beforerequest(request, response, next) {
this.requesttime = new date().valueof()
next()
}
// 方案1. 修改原handler处理逻辑,进行耗时的统计,然后end发送数据
app.get('/a', beforerequest, function(request, response) {
// 请求耗时的统计
console.log(
`${request.url} duration: ${new date().valueof() - this.requesttime}`
)
response.end('xxx')
})
// 方案2. 将输出数据的逻辑挪到一个后置的中间件中
function afterrequest(request, response, next) {
// 请求耗时的统计
console.log(
`${request.url} duration: ${new date().valueof() - this.requesttime}`
)
response.end(this.body)
}
app.get(
'/b',
beforerequest,
function(request, response, next) {
this.body = 'xxx'
next() // 记得调用,不然中间件在这里就终止了
},
afterrequest
)
无论是哪一种方案,对于原有代码都是一种破坏性的修改,这是不可取的。
因为express采用了response.end()的方式来向接口请求方返回数据,调用后即会终止后续代码的执行。
而且因为当时没有一个很好的方案去等待某个中间件中的异步函数的执行。
function a(_, _, next) {
console.log('before a')
let results = next()
console.log('after a')
}
function b(_, _, next) {
console.log('before b')
settimeout(_ => {
this.body = 123456
next()
}, 1000)
}
function c(_, response) {
console.log('before c')
response.end(this.body)
}
app.get('/', a, b, c)
就像上述的示例,实际上log的输出顺序为:
before a before b after a before c
这显然不符合我们的预期,所以在express中获取next()的返回值是没有意义的。
所以就有了koa带来的洋葱模型,在koa1.x出现的时间,正好赶上了node支持了新的语法,generator函数及promise的定义。
所以才有了co这样令人惊叹的库,而当我们的中间件使用了promise以后,前一个中间件就可以很轻易的在后续代码执行完毕后再处理自己的事情。
但是,generator本身的作用并不是用来帮助我们更轻松的使用promise来做异步流程的控制。
所以,随着node7.6版本的发出,支持了async、await语法,社区也推出了koa2.x,使用async语法替换之前的co+generator。
koa也将co从依赖中移除(2.x版本使用koa-convert将generator函数转换为promise,在3.x版本中将直接不支持generator)
由于在功能、使用上koa的两个版本之间并没有什么区别,最多就是一些语法的调整,所以会直接跳过一些koa1.x相关的东西,直奔主题。
在koa中,可以使用如下的方式来定义中间件并使用:
async function log(ctx, next) {
let requesttime = new date().valueof()
await next()
console.log(`${ctx.url} duration: ${new date().valueof() - requesttime}`)
}
router.get('/', log, ctx => {
// do something...
})
因为一些语法糖的存在,遮盖了代码实际运行的过程,所以,我们使用promise来还原一下上述代码:
function log() {
return new promise((resolve, reject) => {
let requesttime = new date().valueof()
next().then(_ => {
console.log(`${ctx.url} duration: ${new date().valueof() - requesttime}`)
}).then(resolve)
})
}
大致代码是这样的,也就是说,调用next会给我们返回一个promise对象,而promise何时会resolve就是koa内部做的处理。
可以简单的实现一下(关于上边实现的app类,仅仅需要修改callback即可):
callback() {
return (request, response) => {
let { url: path, method } = request
let handlers = this.handlers[path] && this.handlers[path][method]
if (handlers) {
let context = { url: request.url }
function next(handlers, index = 0) {
return new promise((resolve, reject) => {
if (!handlers[index]) return resolve()
handlers[index](context, () => next(handlers, index + 1)).then(
resolve,
reject
)
})
}
next(handlers).then(_ => {
// 结束请求
response.end(context.body || '404')
})
} else {
response.end('404')
}
}
}
每次调用中间件时就监听then,并将当前promise的resolve与reject处理传入promise的回调中。
也就是说,只有当第二个中间件的resolve被调用时,第一个中间件的then回调才会执行。
这样就实现了一个洋葱模型。
就像我们的log中间件执行的流程:
- 获取当前的时间戳requesttime
- 调用next()执行后续的中间件,并监听其回调
- 第二个中间件里边可能会调用第三个、第四个、第五个,但这都不是log所关心的,log只关心第二个中间件何时resolve,而第二个中间件的resolve则依赖他后边的中间件的resolve。
- 等到第二个中间件resolve,这就意味着后续没有其他的中间件在执行了(全都resolve了),此时log才会继续后续代码的执行
所以就像洋葱一样一层一层的包裹,最外层是最大的,是最先执行的,也是最后执行的。(在一个完整的请求中,next之前最先执行,next之后最后执行)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
嗫?暁雲?