|
2 | 2 |
|
3 | 3 | An abstraction over WebSockets that just works. It keeps the connection alive, self-heals from failures, and provides flexibility with application-level protocol, including the client authentication mechanism. |
4 | 4 |
|
5 | | -### Status |
6 | | -work-in-progress; install locally via `npm link` |
| 5 | +### Installation |
| 6 | + |
| 7 | +```bash |
| 8 | +npm install @deilux/websocket-js |
| 9 | +``` |
7 | 10 |
|
8 | 11 | ### Motivation |
9 | 12 | Over the past few years, I’ve had to implement WebSocket communication many times and grew tired of the repetitive boilerplate and chasing edge cases. Many WebSocket libraries were non-starters: too complex and prone to hiding the underlying protocol behind their own abstractions. Cloud-based solutions didn’t fit either — my projects require heavy customization, and at that scale I can build and operate the infrastructure myself. |
@@ -63,6 +66,95 @@ All timing is configurable via the options object: |
63 | 66 | } |
64 | 67 | ``` |
65 | 68 |
|
66 | | -### Roadmap |
67 | | -- Fully encapsulate WebSocket management |
68 | | -- Support for RPC-style calls |
| 69 | +### GreatWebSocket |
| 70 | + |
| 71 | +`GreatWebSocket` is the main class you'll use. It wraps `AlwaysConnected` and adds: |
| 72 | +- Convenient `send()` method with connection checking |
| 73 | +- RPC-style request/response via `call()` and `tryHandleAsControlMessage()` |
| 74 | +- Connection state events |
| 75 | + |
| 76 | +#### Basic usage |
| 77 | + |
| 78 | +```typescript |
| 79 | +import { GreatWebSocket, ConnectionState } from '@deilux/websocket-js'; |
| 80 | + |
| 81 | +const ws = new GreatWebSocket( |
| 82 | + 'wss://api.example.com/ws', |
| 83 | + |
| 84 | + // Called when transport connects — do your handshake here |
| 85 | + async () => { |
| 86 | + ws.send(JSON.stringify({ type: 'auth', token: 'my-token' })); |
| 87 | + // Return true when handshake succeeds |
| 88 | + return true; |
| 89 | + }, |
| 90 | + |
| 91 | + // Called for every incoming message |
| 92 | + (socket, ev) => { |
| 93 | + const message = JSON.parse(ev.data); |
| 94 | + |
| 95 | + // First, check if it's an RPC response |
| 96 | + if (ws.tryHandleAsControlMessage(message)) { |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + // Otherwise, handle as a regular message |
| 101 | + console.log('Received:', message); |
| 102 | + }, |
| 103 | + |
| 104 | + // Called periodically to send outbound heartbeat |
| 105 | + (socket, interval) => { |
| 106 | + socket.send(JSON.stringify({ type: 'ping' })); |
| 107 | + }, |
| 108 | +); |
| 109 | + |
| 110 | +// Listen for state changes |
| 111 | +ws.addEventListener('statechange', (ev) => { |
| 112 | + console.log('Connection state:', ev.state); |
| 113 | +}); |
| 114 | + |
| 115 | +// Start the connection |
| 116 | +ws.activate(); |
| 117 | + |
| 118 | +// Send messages (returns false if not connected) |
| 119 | +ws.send(JSON.stringify({ type: 'hello' })); |
| 120 | + |
| 121 | +// Stop when done |
| 122 | +ws.shutdown(); |
| 123 | +``` |
| 124 | + |
| 125 | +#### RPC-style commands |
| 126 | + |
| 127 | +Define commands by implementing the `RemoteCommand` interface: |
| 128 | + |
| 129 | +```typescript |
| 130 | +import { RemoteCommand, GreatWebSocket } from '@deilux/websocket-js'; |
| 131 | + |
| 132 | +class JoinRoomCommand implements RemoteCommand { |
| 133 | + private messageId = crypto.randomUUID(); |
| 134 | + |
| 135 | + constructor(private roomId: string) {} |
| 136 | + |
| 137 | + execute(ws: GreatWebSocket): string { |
| 138 | + ws.send(JSON.stringify({ |
| 139 | + id: this.messageId, |
| 140 | + type: 'join_room', |
| 141 | + roomId: this.roomId, |
| 142 | + })); |
| 143 | + return this.messageId; |
| 144 | + } |
| 145 | + |
| 146 | + responseMatches(message: unknown): boolean { |
| 147 | + return (message as any)?.id === this.messageId; |
| 148 | + } |
| 149 | + |
| 150 | + handleResponse(message: unknown): string { |
| 151 | + return (message as any).status; // Return whatever you need |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +// Usage |
| 156 | +const status = await ws.call(new JoinRoomCommand('room-123')); |
| 157 | +console.log('Joined with status:', status); |
| 158 | +``` |
| 159 | + |
| 160 | +The `call()` method returns a Promise that resolves when a matching response arrives. |
0 commit comments