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 pattern
1class Pipeline {
2 constructor() {
// Array to store middleware functions
3 this.middlewares = [];
4 }
5 use(fn) {
// Add middleware to the pipeline
6 this.middlewares.push(fn);
// Return this for chaining
7 return this;
8 }
9 async execute(context) {
// Track current middleware index
10 let index = 0;
// Create next function to call next middleware
11 const next = async () => {
// If more middlewares exist, execute them
12 if (index < this.middlewares.length) {
// Run the current middleware, advance index, and pass next so it can continue the chain
13 await this.middlewares[index++](context, next);
14 }
15 };
// Start the middleware chain
16 await next();
// Return the modified context
17 return context;
18 }
19}
20
// Create pipeline instance
21const pipeline = new Pipeline();
// Add middlewares
22pipeline
// First middleware sets ctx.a = 1, then calls next
23 .use(async (ctx, next) => { ctx.a = 1; await next(); })
// Second middleware sets ctx.b = ctx.a + 1 = 2
24 .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

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

More JavaScript examples at level 5

← JavaScript typing practice