Websocket api with serverless framework (BlitzJs)?

Viewed 394

I am using a serverless framework Blitz.js for my app. However, now I want to implement a notification system so the user is notified of any updates. As Blitz.js is serverless, I am not sure how to proceed.

Apologies for the open-ended question, however, I wondered if there is a way/ guide to implement Web-Socket or some kind of polling to inform users?

Secondly, how would one integrate a backend server with a serverless framework like Blitz.

Update: (sharing my thoughts)

The way I see it is that the system would work something like the following. The serverless communication between front-end & serverless would continue as is, now the backend server (if really needed for notification/ polling), would communicate with serverless & forward that on to front-end.

enter image description here

1 Answers

WebSockets are a way for browser-resident code to establish a persistent connection to, well, a server. So you're doing something slightly strange and certainly pioneering trying to use it with a serverless framework.

But, WebSocket connections are http (or https) connections. So if your serverless instance endures until all connections are closed, you can conceivably have a connection between your user's browser and your serverless instance. If you can get your hands on the server object in your blitz server-side code you can use npm ws to set up a WebSocket listener.

const requestIp = require( 'request-ip' )
const ws = require('ws' )

...

const wss = new ws.Server({ server });
wss.on('connection', function connection(ws, request) {
  const url = new URL( request.url, 'wss://example.com', true )
  const path = url.pathname
  const clientIp = requestIp.getClientIp( request )
  console.log ('connected to: %s from %s', path, clientIp) 

  ws.on('message', function incoming(message) {
    console.log('received: %s from %s', message, clientIp);
  })

  ws.on('close', function close (code, reason) {
  console.log ('closed: %s from %s', reason , clientIp) 
  })
 
  ws.send('something');
});
Related