Always felt express
This kind of streaming processing is very vivid , It's like a processing line , Each link completes its own work for different parts of the same product , Finally, we get a finished product . Today we're going to implement a simple 【 Middleware queue 】.

One . API layer

*
Initialization method
let middleware = new MiddleWare();
*
How to add middleware functions
//Fn For added Middleware middleware.use(Fn);
*
Start middleware queue
middleware.start(req, res);
Two . Definition of core class
class MiddleWare{ constructor(){ this.queue = [];// It is used to store middleware queue } // Add Middleware
use(fn){ this.queue.push(fn);// Add custom middleware to the queue } // Executing Middleware in sequence start(req, res){ let i
= 0;// Execution pointer // Actuator const next = (err)=>{ // If there is an error, the error message will be displayed in the response Go on and exit directly if(err){
res.hasError = true; res.data = err.toString(); return; }
// If there are no errors, check to see if you are at the end of the line , If not, continue to execute the next middleware if(i < this.queue.length){
this.queue[i++](req, res, next); /* take next Pass in the currently executing function directly as a callback
The current execution function is executed to any step , Through active call next Method to pass the relevant information to the next middleware .*/ }else{ // If it's at the end of the team, it's over
console.log('finish'); } } // Start the first one next(); } }
Three . use use Method to add middleware
// Add the first Middleware /* Here's a basic approach to error trapping , When an error occurs in the middleware , An error is caught and passed in next */
middleware.use(function(req, res, next){ try{ req.addon1 = 'I add something';
}catch(err){ next(err); } next(); }); // Add a 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(); });
Four . Class of consumption definition

“ consumption ” This word is recently learned , I think it's very pretentious X, So install it here ~
let req = {}; let res = {}; let result = middleware.start(req,res);
console.log(req, res);
Five . View run results

You can see different results when an error occurs and when you respond normally :



Six . Running on the server side

use node Make one web Server, that's too casual ~
const http = require('http'); // A bunch of code on it 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 accessing the server, the custom message can be sent to the foreground ):