I have researched the topic for hours on Google and books and I could only find very specific implementations. I'm struggling to write a simple Middleware class in node JS with only plain vanilla javascript (no additional module like async, co,..). My goal is to understand how it works not to get the most optimised code.
I would like something as simple as having a string and adding new string to it thru the use of middleware.
The class
"use strict";
class Middleware {
constructor() {
this.middlewares = [];
}
use(fn) {
this.middlewares.push(fn);
}
executeMiddleware(middlewares, msg, next) {
// This is where I'm struggling
}
run(message) {
this.executeMiddleware(this.middlewares, message, function(msg, next) {
console.log('the initial message : '+ message);
});
}
}
module.exports = Middleware;
A possible usage
const Middleware = require('./Middleware');
const middleware = new Middleware();
middleware.use(function(msg, next) {
msg += ' World';
next();
});
middleware.use(function(msg, next) {
msg += ' !!!';
console.log('final message : ' + msg);
next();
});
middleware.run('Hello');
As a result the msg variable will end up being : 'Hello World !!!'
For those looking for a working example.
// MIDDLEWARE CLASS
"use strict";
let info = { msg: '' };
class Middleware {
constructor() {
this.middlewares = [];
}
use(fn) {
this.middlewares.push(fn);
}
executeMiddleware(middlewares, data, next) {
const composition = middlewares.reduceRight((next, fn) => v => {
// collect next data
info = data;
fn(info, next)
}, next);
composition(data);
}
run(data) {
this.executeMiddleware(this.middlewares, data, (info, next) => {
console.log(data);
});
}
}
module.exports = Middleware;
Usage example :
// index.js
const Middleware = require('./Middleware');
const middleware = new Middleware();
middleware.use(function(info, next) {
info.msg += ' World';
next();
});
middleware.use(function(info, next) {
info.msg += ' !!!';
next();
});
// Run the middleware with initial value
middleware.run({msg: 'Hello'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With