-
Notifications
You must be signed in to change notification settings - Fork 43
Middlewares Functions TypeScript
JavaScript | TypeScript
Page Content:
- Verify Connecting User
- Verify Subscribing User
- Listen to all Publish events
- Communicate between Workers and Machines
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 => {})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
})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)
})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
})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')💥 We would really appreciate if you give us stars ⭐ (on all our repositories):
For you to give the stars ⭐ is not hard, but for us, it is a huge motivation to work harder and improve the project. Thank you very much 😄.