The basic implementation of express middleware system

Keywords: Javascript Web Server JSON

I always think that express middleware system is very vivid in this kind of flow processing, just like the processing pipeline, each link is completing its own work for different parts of the same product, and finally gets a finished product. Today, we will implement a simple [middleware queue].

I. API level

  • Initialization method

    let middleware = new MiddleWare();
  • How to add middleware functions

    //Fn is the middleware to be added
    middleware.use(Fn);
  • Start middleware queue

    middleware.start(req, res);

2, Definition of core class

class MiddleWare{
    constructor(){
        this.queue = [];//Used to store middleware queues
    }
    
    //Add Middleware
    use(fn){
         this.queue.push(fn);//Queue custom Middleware
    }
    
    //Execute Middleware in order
    start(req, res){
        let i = 0;//Execution pointer
        
        //Actuator
        const next = (err)=>{
            //If there is an error, hang the error message on the response and exit directly
            if(err){
                res.hasError = true;
                res.data = err.toString();
                return;
            }
            
            //If there is no error, check whether it reaches the end of the team. If not, continue to execute the next middleware
            if(i < this.queue.length){
                this.queue[i++](req, res, next);
                /*Pass next directly to the currently executed function as a callback
                 At any step of the current execution function, relevant information can be transferred to the next middleware by actively calling the next method.*/
            }else{
                //If it's at the end of the team, it's over
                console.log('finish');
            }
            
        }
        //Start the first
        next();
    }
}

3, Using the use method to add Middleware

//Add the first Middleware
/*
A basic error capture method is shown here. When an error occurs in the middleware, it will catch the error and pass it to next
*/
middleware.use(function(req, res, next){
    try{
       req.addon1 = 'I add something';  
    }catch(err){
       next(err);
    }
    next();
});

//Add second Middleware
middleware.use(function(req, res, next){
     res.addon2 = 'I add something more';
     next();
});

//Add a third Middleware
middleware.use(function(req, res, next){
     if (req.addon2) {
       delete req.addon2;
     }
     res.addon3 = 'I add something a lot';
     next();
});

4, Consumption defined class

The word "consumption" has been learned recently. I think it's very loaded with X, so I'll also install it here~

let req = {};
let res = {};
let result = middleware.start(req,res);
console.log(req, res);

5, View run results

You can see different results when there are errors and normal responses:

6, Running on the server side

It's too casual to start a web server with a node~

const http = require('http');
//A bunch of code above
http.createServer(function(req, res){
    let result = {};
    middleware.start(req, result);
    res.end(JSON.stringify(result));
}).listen(9527);

Take a look at the effect (when visiting the server, the custom message can be sent to the front desk):

Posted by Gamerz on Sat, 28 Dec 2019 10:42:11 -0800