Skip to content

Commit 49992d5

Browse files
committed
🪝 Adding interceptor & long-polling to send responses from server to listening clients
1 parent 70d1f84 commit 49992d5

3 files changed

Lines changed: 88 additions & 4 deletions

File tree

stubs/lrm/expressServer.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const bodyParser = require('body-parser');
1111
const OpenApiValidator = require('express-openapi-validator');
1212
const logger = require('./logger');
1313
const config = require('./config');
14+
const interceptor = require('express-interceptor');
1415

1516
class ExpressServer {
1617
constructor(port, openApiYaml) {
@@ -46,12 +47,37 @@ class ExpressServer {
4647
res.status(200);
4748
res.json(req.query);
4849
});
50+
// Send back info from backend to client using long polling
51+
// 1. Create long polling endpoint
52+
const longPoll = require("express-longpoll")(this.app)
53+
longPoll.create("/poll");
54+
55+
// 2. Intercept all responses (to server-server calls) and send them to the client through long polling endpoint
56+
const finalLongPollingInterceptor = interceptor(function (req, res) {
57+
return {
58+
isInterceptable: () => true,
59+
// Sends response to the client through long polling endpoint
60+
intercept: function (body, send) {
61+
const data = {
62+
code: res.statusCode,
63+
body
64+
};
65+
console.log(data);
66+
longPoll.publish("/poll", data);
67+
send(body);
68+
}
69+
};
70+
})
71+
// Add the interceptor middleware
72+
this.app.use(finalLongPollingInterceptor);
4973
}
5074

5175
launch() {
5276
this.app.use(
5377
OpenApiValidator.middleware({
5478
apiSpec: this.openApiPath,
79+
// Automatic mapping of OpenAPI endpoints to Express handler functions
80+
// Ref.: https://github.com/cdimascio/express-openapi-validator/wiki/Documentation#example-express-api-server-with-operationhandlers
5581
operationHandlers: path.join(__dirname),
5682
fileUploader: {dest: config.FILE_UPLOAD_PATH},
5783
})

stubs/lrm/package-lock.json

Lines changed: 60 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

stubs/lrm/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
"cookie-parser": "^1.4.4",
2121
"cors": "^2.8.5",
2222
"express": "^4.16.4",
23+
"express-interceptor": "^1.2.0",
24+
"express-longpoll": "^0.0.6",
2325
"express-openapi-validator": "^5.0.0",
2426
"js-yaml": "^3.3.0",
2527
"ono": "^5.0.1",

0 commit comments

Comments
 (0)