Skip to content

Commit f0af18b

Browse files
add a middleware manager based on socket.
1 parent 8c4c579 commit f0af18b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

middlewareManager.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* A middleware Manager based on socket.
3+
* */
4+
"use strict";
5+
6+
7+
module.exports = class ZmqMiddlewareManager {
8+
constructor(socket) {
9+
this.socket = socket;
10+
this.inboundMiddleware = []; //[1]
11+
this.outboundMiddleware = [];
12+
socket.on('message', message => { //[2]
13+
this.executeMiddleware(this.inboundMiddleware, {
14+
data: message
15+
});
16+
});
17+
}
18+
19+
send(data) {
20+
const message = {
21+
data: data
22+
};
23+
24+
this.executeMiddleware(this.outboundMiddleware, message,
25+
() => {
26+
this.socket.send(message.data);
27+
}
28+
);
29+
}
30+
31+
use(middleware) {
32+
if (middleware.inbound) {
33+
this.inboundMiddleware.push(middleware.inbound);
34+
}
35+
if (middleware.outbound) {
36+
this.outboundMiddleware.unshift(middleware.outbound);
37+
}
38+
}
39+
40+
executeMiddleware(middleware, arg, finish) {
41+
function iterator(index) {
42+
if (index === middleware.length) {
43+
return finish && finish();
44+
}
45+
middleware[index].call(this, arg, err => {
46+
if (err) {
47+
return console.log('There was an error: ' + err.message);
48+
}
49+
iterator.call(this, ++index);
50+
});
51+
}
52+
53+
iterator.call(this, 0);
54+
}
55+
};

0 commit comments

Comments
 (0)