laitimes

Koa Parsing Koa Introduces Self-Positioning Middleware Processing Logic Error Handling Logic Smaller Core Code Koa Parsing Koa Initialization Application Example app.use() Add Middleware app.listen() Listening--Core Logic Parsing createContextkoa-compose Implementation of onion Circle Model Parsing HandleRequest Summary

author:Flash Gene
Koa Parsing Koa Introduces Self-Positioning Middleware Processing Logic Error Handling Logic Smaller Core Code Koa Parsing Koa Initialization Application Example app.use() Add Middleware app.listen() Listening--Core Logic Parsing createContextkoa-compose Implementation of onion Circle Model Parsing HandleRequest Summary

On koa's website, slogan is: a next-generation web development framework based on the node.js platform. We all know that both koa and express were born out of the same team. How to parse this slogan?

All the words in the slogan that contain the meaning of "compare" can be understood as relative to express. The so-called "next generation", "smaller" and "faster" all refer specifically. Let's take a look at the download volume comparison between express and koa at this stage:

Koa Parsing Koa Introduces Self-Positioning Middleware Processing Logic Error Handling Logic Smaller Core Code Koa Parsing Koa Initialization Application Example app.use() Add Middleware app.listen() Listening--Core Logic Parsing createContextkoa-compose Implementation of onion Circle Model Parsing HandleRequest Summary

It can be seen that the market share and download volume (and growth rate) of express are much higher than that of koa. So it's not an exaggeration to call yourself the "next generation" (of course, it's debatable whether this data level is fair).

At the same time, unlike Express, which includes a basic business processing framework within express, koa only contains the core processing logic of middleware known as the "onion circle model". Koa expects more business modules to be sounded by the community. In this way, it is more appropriate to think of koa as the built-in connect before express (connect has been removed internally in express 4). However, the "smaller" koa positioning is more explicit, and some prominent features within it have also made developers happy.

Next, let's take a closer look at how koa differs from express. Only by understanding the difference will we understand the characteristics of koa better.

On the official koa page, there is a description of koa targeting:

An excerpt from the web translates as follows:

Conceptually, koa intends to "fix and replace node", while express does "enhance node". Koa uses the promise and async functions to get rid of callback hell and simplify exception handling logic. It exposes its own ctx.request and ctx.response objects instead of node's req and res objects.

Express, on the other hand, enhances the req and res objects of node by adding additional properties and methods, and introduces many framework-on-the-shelf features, such as routing and templating, which koa does not do.

Whether its implementation is in line with the positioning, you can see for yourself.

In essence, the difference between koa and express 4 is the following two points:

koa uses promise + async/await to handle middleware pass logic, while express 4 uses callback functions to handle middleware pass logic.

Koa goes through all the middleware processing logic to finally return the request; express 4 returns the request when it encounters res.send().

With promise support for the async/await notation in the new es specification, koa is perfect for supporting asynchronous processing and getting rid of callback hell. The following simulation implementation, looking at the difference in code, you can appreciate the difference between the two.

Inside koa, since it is an onion circle model, the normal middleware processing process can not handle the error logic, only the first middleware in the middleware array is set as the error function middleware. In express 4, error handling logic needs to be included in every normal middleware and thrown through the next() function, otherwise the error will be hidden.

Unlike express 4, which includes neat web tools (routes, templates, etc.), koa focuses only on the core code. So it's smaller.

A simple description does not give us a deeper understanding of the principles of koa. Let's try to look at the source code. The simplest demo code:

Here, we want to go to the source code to figure out a few things:

In a koa app, we build an instance app by const app = new koa(). Core code (with deletions):

The process of initializing an app instance can be seen by adding properties such as context, request, response, middleware, and so on to the app instance. In this initialization process, koa will mount the methods provided by koa to the corresponding location, which is convenient for calling in the code.

Here the type of the incoming function is checked, and if it is an old generator function type, it is converted and then placed directly in the array of middleware. The middleware in the array is executed one after another in each request.

The server is created only when the listen function is executed:

In the http module of node, for each request, it goes to the callback function callback. So this callback is used to handle the actual request. Let's take a look at what callback does:

The content here is not simple, involving several points:

The main thing here is to clarify the content of the context mount, which is generated every request. As you can see from the code:

Each app instance app will have a corresponding context, request, response instance (that is, this.xxx). Each request creates its own instance based on those instances. The purpose of this is to not pollute global variables.

Attach node's native req, res, and this to context, request, response.

The created context is returned, passing in the first argument of all middleware as the context of this request.

Focus on point 2, why you want to mount these properties. In addition to convenience, we can also know by looking at the source code resquest.js response .js files: all of these accesses are proxies, and the final access is node's native req, res.

Next, let's take a look at how the koa-compose plugin in the source code implements the onion circle model:

In simple terms, the middleware is executed one by one in compose based on the variable i, recursively. The whole process is not difficult to understand, and the implementation is more ingenious. It is worth noting that the return value of each dispatch() is promise. You can refer to the following GIF to go through the implementation of the above code.

Koa Parsing Koa Introduces Self-Positioning Middleware Processing Logic Error Handling Logic Smaller Core Code Koa Parsing Koa Initialization Application Example app.use() Add Middleware app.listen() Listening--Core Logic Parsing createContextkoa-compose Implementation of onion Circle Model Parsing HandleRequest Summary

Let's see, having the context information for each request context and the middleware logic after compose, let's see how the request is finally handled:

Execute the compose-followed middleware function, and finally execute the respond method. Upon review, it is clear that the response is mainly encapsulated and assigned to context.res.end(body).

In summary, we briefly introduced koa; at the same time, by parsing the execution process of the demo file, we glimpsed some of the relevant principles of koa implementation from the source code level. At this point, we have finished the introduction and analysis of koa. In the process of writing down this article, I will understand the whole process better and hope it will be helpful to you!

Read on