当前位置:网站首页>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 .
边栏推荐
- 关于IP定位查询接口的测评Ⅲ
- Cache avalanche and cache penetration solutions
- Speech signal processing - Fundamentals (V): Fourier transform
- 盘点那些具有特色的写作软件
- Esp32-c3 introductory tutorial question ⑨ - core 0 panic 'ed (load access fault) Exception was unhandled. vfprintf. c:1528
- Our company has used this set of general solutions for 7 years, and has opened up dozens of systems, a stable batch!
- "New digital technology" completed tens of millions of yuan of a + round financing and built an integrated intelligent database cloud management platform
- TypeScript ReadonlyArray(只读数组类型) 详细介绍
- EMC-浪涌
- A theoretical defect of relative position coding transformer and Its Countermeasures
猜你喜欢

揭秘得物客服IM全链路通信过程

HMS core audio editing service 3D audio technology helps create an immersive auditory feast

Stm32f407zgt6 uses SDIO mode to drive SD card

谁还记得「张同学」?

Alibaba cloud lifeifei: China's cloud database has taken the lead in many mainstream technological innovations abroad

如何通过GDB分析Native Crash

R language view version R package view version
![[xi'anjiaotonguniversity] information sharing of the first and second postgraduate entrance examinations](/img/06/df5a64441814c9ecfa2f039318496e.jpg)
[xi'anjiaotonguniversity] information sharing of the first and second postgraduate entrance examinations

60 个神级 VS Code 插件!!

关于IP定位查询接口的测评Ⅲ
随机推荐
60 个神级 VS Code 插件!!
Stm32f407zgt6 uses SDIO mode to drive SD card
Wechat Emoji is written into the judgment, and every Emoji you send may become evidence in court
Oracle NetSuite 助力 TCM Bio,洞悉数据变化,让业务发展更灵活
Lucene full text search toolkit learning notes summary
A quietly rising domestic software, low-key and powerful!
【模式识别大作业】
The first batch in China! Alibaba cloud native data Lake products have passed the evaluation and certification of the ICT Institute
Uncover the whole link communication process of customer service im
60 divine vs Code plug-ins!!
「运维有小邓」用户个人资料管理
Shell first command result is transferred to the second command delete
10天学会flutter DAY10 flutter 玩转 动画与打包
Summer vacation study record
Introduction to China Mobile oneos development board
H3C switch emptying configuration
Multiparty cardinality testing for threshold private set-2021: Interpretation
R language view version R package view version
Speech recognition - Fundamentals (I): introduction [speech to text]
Shutter from zero 004 button assembly