The necessity of studying KOA
Koa is a small and robust Web development framework created by the original team of Express. Because of its advantages, the core of many Web frameworks such as EGGJS is also driven by KOA. Being familiar with KOA code is not only helpful for koA development. It also provides insight into more powerful frameworks such as EggJS.
- Knowledge review
- The code structure
Knowledge review
Prototype is the core of javascript and one of the key points to understand javascript in depth. A delegate is a way of programming that simplifies what we do.
1.1 First declare the “parent class” (or the prototype of a subclass)
const Car = {
get name() {
return this.engine.name;
},
start: function() {
return `The ${this.engine.name} start`; }};Copy the code
1.2 Using a parent class to create a subclass (the parent class is on the prototype chain of the subclass)
const BMW = Object.create(Car);
Copy the code
1.3 Dynamically add attributes to subclasses
BMW.engine = {
name: 'v8'};Copy the code
1.5 Calling a subclass’s method
BMW.name; // 'v8'
BMW.start(); // 'v8 start'
Copy the code
1.6 Defining proxy Objects
const BMWPHONE = {};
Copy the code
1.7 Defining proxy methods
function Delegate(source, target) {
this.source = source;
this.target = target;
}
Delegate.prototype.method = function(name) {
const target = this.target;
const source = this.source;
source[name] = function() {
return this[target][name].apply(this[target], arguments);
};
};
Copy the code
1.8 Execute target methods on proxy objects
const delegate = new Delegate(BMWPHONE, 'BMW');
delegate.method('start');
BMWPHONE.BMW = BMW;
BMWPHONE.start();
Copy the code
The Car parent class is defined, and BMW inherits the Car method and gives BMW an awesome engine that can now be started manually via BMW. Now BMW is developing a mobile phone that starts manually using a mobile operator agent.
The reason for using the above example (where you can see the huge difference between JS and static languages) is that three of the four files in KOA are related to prototypes and proxies.
The code structure
Koa is very small, there are only 4 files in total, and the function of each file is very simple. The file name clearly reflects the function of the file.
Koa file structure
├── ├─ ├─ ├─ request.js ├─ ├.js ├── response.jsCopy the code
-
request.js
A large number of GET methods are provided for HTTP request objects. Files are used to obtain properties of the request object. See 1.1.
-
response.js
A large number of set methods are provided for the response object, mainly for HTTP. This file is mainly used to set the properties of the Response object, see 1.1.
-
context.js
Koa introduced the concept of context object, namely CTX. The so-called context object here is actually the union of request and Response objects. Request and Response respectively delegate their methods to CTX in the form of proxy (refer to 1.8). That way we can use CTX to manipulate both objects at the same time to simplify things.
-
application.js
This file is the core of the entire KOA and has two main functions in short: to mount real requests to CTX and to encapsulate the execution order of the middleware
createContext(req, res) {
const context = Object.create(this.context);
const request = context.request = Object.create(this.request);
const response = context.response = Object.create(this.response);
context.app = request.app = response.app = this;
context.req = request.req = response.req = req;
context.res = request.res = response.res = res;
request.ctx = response.ctx = context;
request.response = response;
response.request = request;
}
Copy the code
In this case, createContext is the operation from section 1.3 above – inheriting the method on the prototype chain and preparing data for the method on the prototype chain. There is a lot of redundant mount here (redundant for express partial compatibility), some of which can be omitted if you only need CTX.
module.exports = compose;
function compose(middleware) {
return function(context, next) {
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); }}}; }Copy the code
Koa middleware is characterized by reverse execution, or the Onion model. The compose method above is the code that implements the Onion model. In simple terms, the method body of the next middleware is replaced with the next parameter of the last middleware. The compose method is one of the most difficult parts of KOA to understand.
app.use(async function1(ctx, next) {
console.log(1.1);
next();
console.log(1.2);
})
app.use(async function2(ctx, next) {
console.log(2.1);
next();
console.log(2.2);
})
Copy the code
The actual code executed after the compose function processing can be seen as:
(async function1(ctx) {
console.log(1.1);
/ / the next part
(async function2(ctx) {
console.log(2.1); . console.log(2.2)
}
)(ctx)
conosle.log(1.2);
})(ctx)
Copy the code
So you can see the characteristics of the Onion model: the middleware that registers first is located at the outermost part of the model. In fact, the KOA does two main things:
- Encapsulation CTX
- Assemble middleware to implement the onion model of reverse execution.
conclusion
Compared to HAPI and EggJS, KOA is too small to be considered a framework and can be considered a library, but this does not prevent the development of the KOA ecosystem.
Koa can be seen as an implementation of the idea that Express was originally a large, comprehensive framework that slowly decoubled functionality from middleware. Koa is very friendly to people who use NodeJS to develop web for the first time. However, there are also some problems, such as too flexible programming, resulting in a wide variety of programming methods, no unified standard, and high learning costs between different engineering codes.
For starters, it is recommended to start with KOA and use different middleware to implement different functions, which is a great help in understanding Web development. When you have a certain amount of accumulation and experience, you can agree on your own KOA programming rules. When your own programming rules cannot meet your requirements, you can start with the real framework.
Pay attention to wechat public number: KnownsecFED, code to get more quality dry goods!