Middleware Pattern in JavaScript
Level 5507 keystrokes
Middleware pattern chains handlers that can transform data or control flow sequentially.
JavaScript code
// Pipeline class implementing middleware pattern1class Pipeline {2 constructor() { // Array to store middleware functions3 this.middlewares = [];4 }5 use(fn) { // Add middleware to the pipeline6 this.middlewares.push(fn); // Return this for chaining7 return this;8 }9 async execute(context) { // Track current middleware index10 let index = 0; // Create next function to call next middleware11 const next = async () => { // If more middlewares exist, execute them12 if (index < this.middlewares.length) { // Run the current middleware, advance index, and pass next so it can continue the chain13 await this.middlewares[index++](context, next);14 }15 }; // Start the middleware chain16 await next(); // Return the modified context17 return context;18 }19}20 // Create pipeline instance21const pipeline = new Pipeline();// Add middlewares22pipeline // First middleware sets ctx.a = 1, then calls next23 .use(async (ctx, next) => { ctx.a = 1; await next(); }) // Second middleware sets ctx.b = ctx.a + 1 = 224 .use(async (ctx, next) => { ctx.b = ctx.a + 1; await next(); });25 // Execute and log result: { a: 1, b: 2 }26pipeline.execute({}).then(console.log);Output
{ a: 1, b: 2 }Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 17)× 17;× 15.× 14{× 9}× 9=× 9,× 3+× 3>× 3