實現一個簡易的express中間件
阿新 • • 發佈:2018-09-21
str 修改 clas middle 分享圖片 next 測試 inf 返回
代碼:
// 通過閉包實現單例 const Middlewave = (function(){ let instance; class Middlewave{ constructor() { this.stack = []; // 中間件調用棧 return instance || (instance = this); // 返回單例 } // 註冊中間件 use(...funcs) { // 將中間件push到stack調用棧中 funcs.forEach(func => this.stack.push(func)); } // 調用下一個中間件 next() { if (this.stackCopy[0]) { // 取出當前中間件 const curWave = this.stackCopy.shift(); // 執行當前中間件 // next綁定this,防止this指向被修改 curWave(this.req, this.res, this.next.bind(this)); } } init(req, res) { this.req = req; this.res = res; // 復制一份中間件調用棧調用棧 this.stackCopy = this.stack.map(item => item); // 執行下一步 this.next(); } } return Middlewave; })();
測試:
const app = newMiddlewave(); function middlewave_a(req, res, next) { req.a = true; res.a = true; console.log(‘a‘, req, res); next(); } function middlewave_b(req, res, next) { req.b = true; res.b = true; console.log(‘b‘, req, res); next(); } function middlewave_c(req, res, next) { req.c = true; res.c = true; console.log(‘c‘, req, res); } function middlewave_d(req, res, next) { req.d = true; res.d = true; console.log(‘d‘, req, res); next(); } app.use(middlewave_a); app.use(middlewave_b); app.use(middlewave_c); app.use(middlewave_d); app.init({name: ‘a‘}, { name: ‘a‘}); app.init({name: ‘b‘}, { name: ‘b‘}); app.init({name: ‘c‘}, { name: ‘c‘});
結果:
實現一個簡易的express中間件