Skip to content
This repository was archived by the owner on Nov 2, 2020. It is now read-only.

Middlewares Functions TypeScript

Dmitrii Goriunov edited this page Feb 21, 2018 · 4 revisions

JavaScript | TypeScript

Page Content:

Here you can find all middlewares which are supported in ClusterWS. setMiddleware function should be called outside of wss.on('connection', (socket: Socket): void => {}), example:

// setMiddleware code
wss.setMiddleware('middleware name', (): void => {})

// listen on connection to websocket server
wss.on('connection', (socket: Socket): void => {})

Verify Connecting User

If you want to verify the user which is trying to connect to the WebSocket Server you can use verifyConnection middleware function.

wss.setMiddleware('verifyConnection', (info: CustomObject, next: Listener): void => {
     // stop user from connecting to WebSocket Server
     next(false) // wss.on('connection') won't be called

     // or you can proceed it by passing true in callback
     next(true)

     // you can use variable info to find different values and compare for example origin
     console.log(info.origin) // ex: https://localhost
})

Verify Subscribing User

You can verify user which is trying to subscribe to the channels by using onSubscribe middleware function:

wss.setMiddleware('onSubscribe', (socket: Socket, channel: string, next: Listener): void => {
      // You can do validation in here

      // will not subscribe user to the channel
      next(false) 

      // will subscribe user to the channel
      next(true) 
})

Listen to all Publish events

You can use onPublish middleware function to catch all messages which are published to the channels (only if this channel exist on this particular server, worker)

wss.setMiddleware('onPublish', (channel: string, data: any): void => { 
    // channel: name of the channel
    // data: data which were published to the channel
})

Communicate between Workers and Machines

You can communicate across all workers (including on the other machines) through the private communication channel:

// Listen on messages from workers
wss.setMiddleware('onMessageFromWorker', (data: any): void => {
    // execute any code on message form workers
})

// Send message to all workers including current one
// you can call this method from everywhere in your code
wss.publishToWorkers('Any message you want to send to all workers on all machines')

Clone this wiki locally