A, according to Koa
Koa
Is made up ofExpress
The original cast, but compared toExpress
Large and complete,Koa
It’s small and fine.Koa
Not having a lot of frameworks and plugins tied in makes it easier to extend, including the popular onesEggJS
andThinkJS
Are based onKoa
The development of.Koa
Instead of calling Express middleware in the form of callback, it uses our new VERSION of JS features,Koa1
Middleware with our helpco
andgenerator
Features,Koa2
With the help of thePromise
andasync await
Features, better flow control and catch our errors.Koa
providesContext
Object, actually, to our noderequest
andresponse
Object encapsulation, we don’t need a lot of manual handling of ourrequest
andresponse
Object.Context
Is throughout our entire request process, we can middleware needs to pass parameters to hang toContext
On the object. (Chestnut: We can hang user information on it, throughctx.state.user
To operate.)Koa
Middleware execution mechanism:Onion ring model
. It is not executed sequentially, multiple middleware forms oneAfter the advanced
The current middleware controls the execution right of the next middleware, which is very effective for the realization of flow control and post-processing logic.
Ii. Comparison of Koa2 and Koa1
- Middleware management mode:
Koa1
With the help ofco
andgenerator
Managing our middleware,Koa2
With the help ofasync await
Async returnsPromise
Object) manages our middleware. context
Object to obtain:Koa1
throughthis
Object (this.req
.this.res
),Koa2
throughctx
Parameters (ctx.req
.ctx.res
).- Community maturity:
Koa2
The wheels are more mature and ecological thanKoa1
Rich.
Three, for example, analyze the source code
1. The chestnuts
listen
3000
use
koa
console
2. Start with the Listen method
- First, clone the latest Koa source code on Github. Then the source code structure is as follows:
- You can see the whole source code is the core code
lib
Files, we’re in chestnutsrequire('koa')
It’s actually introducedlib/application.js
The inside of theApplication
Class. Now let’s analyze ourslisten
Method implementation, let’s look at this firstApplication
What exactly is in the class:
- We can see that
Application
We have ours under the classlisten
Methods: The methods are as follows:
This.callback() is the input to createServer, which is a function that listens to the request event and receives req and RES, which are our request object and response object. We can infer that this.callback() in listen actually returns a function that takes req and RES.
- Now let’s look at this one
this.callback()
Callback (); callback ();
The compose method is important to control the execution of our middleware
This method takes two parameters: fn, the return result of our compose, and our CTX object. This method is responsible for the processing of our request and the uniform capture and processing of errors.
3. Implement our chestnuts: Take a look at the middleware implementation mechanism
Koa’s middleware implementation mechanism is known figuratively as the Onion Ring model. Let’s run the chestnut code and see what the output looks like.
4. Start by understanding the Use method
Push the middleware function we passed in to the this.middleware array
5. The core of the middleware execution mechanism is compose
Compose (this.middleware) : compose(callback) : compose(this.middleware)
- First, verify that our middleware parameters are correct, whether the array is an array, whether the array items are functions;
- The compose function actually returns a function, which, as mentioned above, is eventually passed to the handleRequest method and then the CTX argument: fnMiddleware(context).
- Returning to the function of our compose return, we receive two arguments: The first is the CTX object passed in by our handleRequest method, and the second, next, is actually a method passed in, which is the last function to process after all middleware is done. The core of this function is to recursively execute our Middleware. To understand this code, you need to understand it
Promise.reslove()
.
Promise.reslove returns a Promise object of fulfillled
// Can be a shortcut to new Promise()
Promise.reslove(fn(context, dispatch.bind(null, i+1)));// Is actually equal to
new Promise((relove, reject) = > {
reslove(fn(context, dispatch.bind(null, i+1)));
})
Copy the code
- Read this function carefully, it isWe define an index (using our closure to change the index one dispatch at a time)“, executes dispatch(0), which is the core of our implementation mechanism, and returns the middleware if it doesn’t get to the last middleware
Promise.reslove(fn(context, dispatch.bind(null, i + 1)))
thefn(context, dispatch.bind(null, i + 1))
That is, execute we passapp.use
Adding the Middleware function,The Middleware function takes two arguments, context and next: the next middleware function, so that if one of the middleware in our KOA doesn’t execute next, any middleware added later won’t. And that’s what formed ourOnion ring model
.
// Core method: recursively call our middlewares, based on Promise for asynchronous process control;
// promise.resolve () returns a thenable object;
// Therefore, the middleware in KOA2 is based on async functions and await the execution of the next middleware method;
return function (context, next) {
// 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, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err)
}
}
}
Copy the code
Four,
- The Koa framework is small and elegant, and its source code is very small, just over a thousand lines. The execution mechanism of middleware is mainly to read the koa-compose code. Multiple middleware will form an advanced and out stack structure, and the current middleware controls the execution right of the next middleware.
- The function of Koa itself may not be able to meet the needs of our daily development. We can assist our development through many third-party packages or custom middleware. (Knowing the middleware mechanism, it is very easy to customize one)
- Koa1 manages our middleware with CO and Generator and Koa2 manages our middleware with async await (async functions return Promise objects).
Five, Koa2 actual combat
Koa2 – mysql-sequelize-jWT – koA2 – mysql-sequelize-jWT
Vi. Front-end Training Guide (I hope it can be helpful to you)
This is a personal blog (front-end training guide) : front-end-Web- Developer – Interview
Vi. Reference documents
- How long before Koa2 replaces Express
- Koa vs Express && Koa1 vs Koa2