洋葱模型
1. app.use()
app.use(async (ctx, next) => {});
// 将中间件放入中间件数组
源码:
use(fn) {
if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
if (isGeneratorFunction(fn)) {
deprecate('Support for generators will be removed in v3. ' +
'See the documentation for examples of how to convert old middleware ' +
'https://github.com/koajs/koa/blob/master/docs/migration.md');
fn = convert(fn);
}
debug('use %s', fn._name || fn.name || '-');
this.middleware.push(fn);
// 将中间件放入中间件数组
return this;
}
2. app.listen()
module.exports = app.listen(config.port, '0.0.0.0', () => {
console.log('进入app');
});
源码:
listen(...args) {
debug('listen');
// this.callback()为connection listener, 当客户端连接上服务器时会触发该函数,即handleRequest
const server = http.createServer(this.callback());
return server.listen(...args);
}/**
* Return a request handler callback
* for node's native http server.
*
* @return {Function}
* @api public
*/callback() {
// 将中间件数组传入koa-compose, 得到一个返回函数,将该函数传入this.handleRequest
const fn = compose(this.middleware);
if (!this.listeners('error').length) this.on('error', this.onerror);
const handleRequest = (req, res) => {
const ctx = this.createContext(req, res);
return this.handleRequest(ctx, fn);
};
return handleRequest;
}/**
* Handle request in callback.
*
* @api private
*/handleRequest(ctx, fnMiddleware) {
const res = ctx.res;
res.statusCode = 404;
const onerror = err => ctx.onerror(err);
const handleResponse = () => respond(ctx);
onFinished(res, onerror);
// fnMiddleware(ctx) 返回promise
/*
return Promise.resolve(fn(context, function next () {
return dispatch(i + 1)
}))
首先执行第一个中间件函数,传入context和next函数,next返回也是返回promise
*/
return fnMiddleware(ctx).then(handleResponse).catch(onerror);
}
3. koa-compose
function compose (middleware) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}/**
* @param {Object} context
* @return {Promise}
* @api public
*/return function (context, next) {
// next 为undefined
// last called middleware #
let index = -1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(context, function next () {
return dispatch(i + 1)
}))
} catch (err) {
return Promise.reject(err)
}
}
}
}
总结
【洋葱模型】整个流程为:
app.use函数将中间件放入中间件数组。当app接收到http请求时,会执行connection listener函数,这个函数中会去执行koa-compose返回的函数(return dispatch(0)),此时会执行第一个中间件函数,传入content和next函数,每个next函数也会返回一个promise。在中间件函数中await next(),即执行下一个中间件函数(return dispatch(i + 1)),直到所有的中间件都执行结束后,将undefined赋值给fn(if (i === middleware.length) fn = next)。
推荐阅读
- 读司马懿,知人间事,品百味人生
- Flutter的ListView
- 一般模型化关系——从模型是什么到如何起作用的基本答案
- 洋葱阅读法(二)
- 2019年的第一次洋葱线下读书会活动
- Pytorch学习|sklearn-SVM 模型保存、交叉验证与网格搜索
- 旅途碎碎念
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 时间管理的任务模型
- 《DOM知识点总结》