1.0.0 • Published 6 years ago

websocket-observer v1.0.0

Weekly downloads
2
License
ISC
Repository
-
Last release
6 years ago

WebsocketObserver

Basically an observer pattern that notifies the clients subscribed

Usage Example

	const WebSocket = require('ws')
	const Observer = require('websocket-observer')

	const wss = new WebSocket.Server({ port: 3000 })
	Observer.setData('')

	wss.on('connection', client => {
		Observer.subscribe(client)
		client.on('message', msg => Observer.setData(data => `${ data }, ${ msg }`))
	})

Methods

subscribe

Saves the client, sets him up to unsusbribe on disconnection and notifies him

setData

Updates the data saved by the observer and broadcasts it to all clients

Can either receive a value(any type)

	Observer.setData({
		msg: 'Message'
	}))

Or a function which receives the current data as paremeter and returns the updated data

	Observer.setData(data => data + msg))

getData

Returns the data

getSubscribers

Returns the subscribers