|
| 1 | +const WebSocketServer = require('ws').WebSocketServer; |
| 2 | +const parse = require('url').parse; |
| 3 | +const mockNotifications = require('./json-server-db.json').notifications; |
| 4 | + |
| 5 | +/** |
| 6 | + * newNotificationObj A notification that is intented to be delivered after Xmsec, |
| 7 | + * instead during the initial 'db' lookup. |
| 8 | + * Part of the `on('connection',()=>{}) callback`. |
| 9 | + */ |
| 10 | +const newNotificationObj = { |
| 11 | + uuid: "ed3c55cc-0f6a-46d8-8b08-59623c949103", |
| 12 | + timestamp: "2022-06-10T11:00:00Z", |
| 13 | + readStatus: "UNREAD", |
| 14 | + message: "A new text message or inner JSON.", |
| 15 | +}; |
| 16 | + |
| 17 | +const responseNotificationObj = { |
| 18 | + uuid: "50522abe-2758-45cd-9ec7-d26573856f6d", |
| 19 | + timestamp: "2022-06-10T12:00:00Z", |
| 20 | + readStatus: "READ", |
| 21 | + message: "Changes accepted.", |
| 22 | +}; |
| 23 | + |
| 24 | + |
| 25 | +/** |
| 26 | + * The websocket part of the mock server along with some http server specific handlings (upgrade, match route). |
| 27 | + * To test connectivity use any ws test client (e.g. postman, or some browser extension and connect to `ws://localhost:4000/feed`). |
| 28 | + * Upon connection, any existing db notifications will be received. After 5 seconds, a new notification will automatically arrive, |
| 29 | + * overriding the old message. |
| 30 | + * Send a test message, e.g. {"userResponse": "UPDATE_BID"} to trigger the 'on message' logic execution. |
| 31 | + * @param {*} httpServer The underlying http Server instance. This will actually serve the ws endpoint(s). |
| 32 | + * @param {*} wsPathName The pathname of the ws capable endpoint |
| 33 | + * @param {*} feedIntervalStep This is an interval to emulate some external event, resulting in the presence of a new notification object. In Xmsec a new notification will arrive, emulating automated real-time message delivery. |
| 34 | + */ |
| 35 | +module.exports = (httpServer, wsPathName = '/feed', feedIntervalStep = 30_000) => { |
| 36 | + const notificationsWS = new WebSocketServer({ noServer: true }); |
| 37 | + let responseTimeout; |
| 38 | + let feedInterval; |
| 39 | + |
| 40 | + notificationsWS.on('connection', function onConnection(ws, connectionRequest) { |
| 41 | + console.log('WebSocket connection established'); |
| 42 | + // Send any existing db notifications. |
| 43 | + ws.send(JSON.stringify({ notifications: mockNotifications })); |
| 44 | + |
| 45 | + feedInterval = setInterval(() => { |
| 46 | + // this could also be a setTimeout since it's just a single, notification item, message emulated. |
| 47 | + ws.send(JSON.stringify({ notifications: [newNotificationObj] })); // send array of objects, to be consistent of what to expect in the client side. |
| 48 | + console.debug('Interval placeholder to send new notifications.'); |
| 49 | + }, feedIntervalStep); |
| 50 | + |
| 51 | + /** |
| 52 | + * Register the on message callback. Executed each time a web app/client, sends data to the ws server. |
| 53 | + */ |
| 54 | + ws.on('message', function onMessage(data) { |
| 55 | + try { |
| 56 | + let dataObj = JSON.parse(data); // assuming json payload |
| 57 | + console.log(`Received message from web client with data: ${data}.`); |
| 58 | + |
| 59 | + // assuming the client sends an object with the 'userResponse' attribute in, set to 'UPDATE_BID'. |
| 60 | + if (dataObj?.userResponse === "UPDATE_BID") { |
| 61 | + responseTimeout = setTimeout(() => { |
| 62 | + ws.send(JSON.stringify({ notifications: [responseNotificationObj] })); |
| 63 | + }, 1_000); |
| 64 | + } |
| 65 | + } |
| 66 | + catch (error) { |
| 67 | + // handle error |
| 68 | + } |
| 69 | + }); |
| 70 | + |
| 71 | + /** |
| 72 | + * Register the on close callback. Cleanup before closing the connection. |
| 73 | + */ |
| 74 | + ws.on('close', () => { |
| 75 | + clearInterval(feedInterval); |
| 76 | + clearTimeout(responseTimeout); |
| 77 | + console.log('WebSocket connection closed.'); |
| 78 | + }); |
| 79 | + }); |
| 80 | + |
| 81 | + httpServer.on('upgrade', function upgrade(request, socket, head) { |
| 82 | + const { pathname } = parse(request.url); |
| 83 | + |
| 84 | + if (pathname === wsPathName) { |
| 85 | + notificationsWS.handleUpgrade(request, socket, head, function done(ws) { |
| 86 | + notificationsWS.emit('connection', ws, request); |
| 87 | + }); |
| 88 | + } else { |
| 89 | + console.log('Closing the socket!!'); |
| 90 | + socket.destroy(); |
| 91 | + } |
| 92 | + }); |
| 93 | +}; |
0 commit comments