当前位置:网站首页>Analysis of KOA - onion model
Analysis of KOA - onion model
2022-06-30 11:47:00 【yanling. zhang】
1. What is? koa?
Koa It's a streamlined node frame , Considered the second generation Node frame , Its biggest feature is the unique middleware process control , It's a typical onion model , Its core work includes the following two aspects :
take node Native req and res Package into a context object .be based on async/await Middleware onion model mechanism .
2.koa1 and koa2 What is the difference in the source code ?
- Koa1 It's using generator、yield The pattern of .
- Koa2 It uses async/await + Promise The pattern of .
3. What is an onion model .
Koa The onion model is based on next() The function is the split point , From the outside to the inside Request The logic of , Then from the inside out Response The logic of , there request The logic of , We can understand it as next Previous content ,response The logic is next What follows the function , It can also be said that every middleware has two processing opportunities . The core principle of onion model is mainly based on compose Method .
Here's the picture :
The following is an example of an onion code :
const Koa = require('koa');
//Applications
const app = new Koa();
// middleware 1
app.use((ctx, next) => {
console.log(1);
next();
console.log(2);
});
// middleware 2
app.use((ctx, next) => {
console.log(3);
next();
console.log(4);
});
app.listen(7000, '0.0.0.0', () => {
console.log(`Server is starting`);
});
// The printing order of middleware is 1 -> 3 -> 4 -> 2
4. The source code parsing
- use Method
When using middleware , First use use Method ,use The method will say that the incoming middleware callback function is stored in middleware Middleware array .
- listen Method
When executed app.listen When listening to the port , In fact, it calls http Modular createServer Method , Then pass in the built-in callback Method , This callback The method will use Method stored middleware The middleware array is passed to compose function .
- compose Method
compose Method is the core of onion model ,compose One of the methods is dispatch Method , On the first call , It executes the first middleware function , When the middleware function is executed, it is called again dispatch function , In other words, it forms a recursive , This is it. next The reason why the next middleware will be executed when the function is executed , So an onion model is formed .
function compose (middleware) {
// context: Context
// next:next function
return function (context, next) {
// last called middleware #
let index = -1
// At the beginning, it was passed in as 0, It will increase in the future
return dispatch(0)
function dispatch (i) {
// If there is no increase , Then it indicates that... Has been executed multiple times
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
// Get the current middleware
let fn = middleware[i]
if (i === middleware.length) fn = next
// When fn When it's empty , It's going to execute next() The later part of the code
if (!fn) return Promise.resolve()
try {
// Execution middleware , Note these two parameters , They are all parameters passed by middleware , The first is context , The second is next function
// That is to say, execution next That is, call dispatch Function
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err)
}
}
}
}
5. Why do you need an onion model ?
Because a lot of times , In a app There are many Middleware , Some middleware need to rely on the results of other middleware , The onion model can guarantee the execution order , If there is no onion model , The order of execution may not be what we expected .
边栏推荐
- Cache avalanche and cache penetration solutions
- [applet practice series] Introduction to the registration life cycle of the applet framework page
- “\“id\“ contains an invalid value“
- Customize an annotation to get a link to the database
- 达梦数据冲刺科创板,或成A股市场“国产数据库第一股”
- 学习redis实现分布式锁—–自己的一个理解
- There are so many kinds of coupons. First distinguish them clearly and then collect the wool!
- The operation and maintenance security gateway (Fortress machine) of Qiming star group once again won the first place!
- STM32F407ZGT6使用SDIO方式驱动SD卡
- Summer vacation study record
猜你喜欢

Record the memory leak of viewpager + recyclerview once

Is the golden cycle of domestic databases coming?

How to analyze native crash through GDB

Stm32f407zgt6 uses SDIO mode to drive SD card

“新数科技”完成数千万元A+轮融资,造一体化智能数据库云管理平台

AutoCAD - len command

Oracle netsuite helps TCM bio understand data changes and make business development more flexible

基于视觉的机器人抓取:从物体定位、物体姿态估计到平行抓取器抓取估计

AUTOCAD——LEN命令

How harmful are these "unreliable" experiences in the postgraduate entrance examination?
随机推荐
Webview,ScrollView滑动冲突咋整
使用cookie技术实现历史浏览记录并控制显示的个数
什么是微信小程序,带你推开小程序的大门
科普達人丨漫畫圖解什麼是eRDMA?
Goto statement jump uninitialized variable: c2362
Customize an annotation to get a link to the database
TypeScript ReadonlyArray(只读数组类型) 详细介绍
数据库 自动增长
Summer vacation study record
OpenMLDB Meetup No.4 会议纪要
【模式识别大作业】
以PolarDB为代表的阿里云数据库以跻身全球第一阵营
Multiparty Cardinality Testing for Threshold Private Set-2021:解读
R语言去重操作unique duplicate filter
Xu Lei expressed three thanks for the most difficult 618 in 19 years
shell第一个命令结果传入第二个命令删除
Set up your own website (13)
1175. prime permutation
Speech recognition - Fundamentals (I): introduction [speech to text]
Automatic database growth