Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  166] [ 4]  / answers: 1 / hits: 7111  / 8 Years ago, sun, september 4, 2016, 12:00:00

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 !!!'


More From » node.js

 Answers
3

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'});

[#26182] Friday, September 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melinal

Total Points: 367
Total Questions: 101
Total Answers: 96

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;