2.1.6 • Published 21 hours ago
wshe v2.1.6
wshe
WS Helper
A simple yet modern websocket client.
Installation
pnpm i wshe
Usage
import { createWSHE } from 'wshe'
const wshe = createWSHE('wss://echo.websocket.org', {
// Pass this to automatically connect on creation
immediate: true
})
// You can also connect manually
wshe.connect()
// You can send something
wshe.send('<eventName>', '<eventPayload>')
// or send raw data
wshe.sendRaw('<rawData>')
wshe.subscribeRaw((data) => {})
// You can listen to messages
const unsubscribe = wshe.subscribe('<eventName>', (payload) => {})
Server implementation
You should implement a server to transfer messages between clients.
And do this on onmessage
to handle heartbeat requests:
import { getHeartbeatResponse, isHeartbeatRequest } from 'wshe/server'
ws.onmessage = (message) => {
if (isHeartbeatRequest(message)) {
ws.send(getHeartbeatResponse(message))
return
}
// do your own logic here..., e.g.
JSON.parse(message)
}
TypeScript Support
This library is written in TypeScript and provides good support for it.
Set message type will be like this:
const wshe = createWSHE<{
foo: {
bar: string
}
baz: {
qux: number
}
}>('...')
wshe.subscribe('foo', (payload) => {
// ^? { bar: string }
})
wshe.subscribe('baz', (payload) => {
// ^? { qux: number }
})
Credits
This project is highly inspired by wsgo.
License
MIT