2.1.6 • Published 21 hours ago

wshe v2.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
21 hours ago

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

2.1.2

1 day ago

2.1.4

22 hours ago

2.1.3

1 day ago

2.1.6

21 hours ago

2.1.5

22 hours ago

2.1.1

2 days ago

2.1.0

2 days ago

1.2.0

3 days ago

1.1.0

3 days ago

1.2.1

3 days ago

2.0.1

3 days ago

2.0.0

3 days ago

1.0.2

19 days ago

1.0.1

1 month ago

1.0.0

1 month ago

0.1.2

1 month ago

0.1.1

1 month ago

0.1.0

1 month ago

0.0.1

1 month ago