socket/README.md
2025-05-03 13:15:03 -04:00

106 lines
3 KiB
Markdown

# @endeavorance/socket
Lightweight reconnecting websocket interface
## ManagedSocket
### `new ManagedSocket(url: string, handlers?: EventHandlers): ManagedSocket`
Create a new `ManagedSocket` instance and connect to the provided URL via WebSocket.
The provided URL should use the `ws://` or `wss://` protocol.
```typescript
import { ManagedSocket } from "@endeavorance/socket";
const mySocket = new ManagedSocket("wss://socket.my-server.web", {
onConnected: () => {},
onMessage: (data: unknown) => {},
onError: (error: SocketError) => {},
onDisconnected: ({wasClean, code, reason}) => {},
});
```
### `.send<T>(data: T)`
Sends the provided data over the socket.
The data can be of any shape as long as it can be serialized (using `JSON.stringify` under the hood).
If `send()` is called on a `ManagedSocket` instance that is not currently connected, it will be enqueued to be sent once the connection is reestablished.
```typescript
const mySocket = new ManagedSocket("...");
mySocket.send("hello!");
mySocket.send({
command: "do-something",
args: ["hello", "world"],
});
```
### `.onMessage: SocketDataHandler`
A function to invoke whenever the socket receives a message meant to be handled by your application.
This handler will be passed the blob of data contained within the message, which is typed as `unknown`.
Your handler function should parse the incoming data to ensure it is of the shape you expect.
```typescript
const handler = (data: unknown) => {
console.log("Got some data: " + data);
}
const mySocket = new ManagedSocket("...");
mySocket.onMessage = handler;
```
### `.onError: SocketErrorHandler`
Provide a function to invoke when the socket encounters a non-catastrophic error.
Not catastrophic errors may occur during the lifecycle of the WebSocket connection, but are different from Catastrophic errors which only occur if the connection was terminated with a non-reconnect code.
This function will be passed a `ManagedSocketError`. If no error handler is set, errors will instead be thrown.
```typescript
const errorHandler = (error: ManagedSocketError) => {
console.error(error);
}
const mySocket = new ManagedSocket("...");
mySocket.onError = errorHandler;
```
### `.onConnected: SocketOpenHandler`
Provide a function to be invoked when the connection is opened.
No arguments are provided to this handler.
### `.onDisconnected: SocketCloseHandler`
Provide a function to be invoked when the connection closes cleanly.
No arguments are provided to this handler.
### `.close()`
Safely close the socket connection.
## `Utilities`
### `wrap<T>(data: T): SocketDataMessage`
Wraps the provided data in a shape to be serialized and sent over the socket.
### unwrap<T>(message: SocketDataMessage): T
Unwraps the provided `SocketDataMessage` to extract the data contained within.
### `deserialize(data: string): SocketMessage`
Attempts to deserialize the provided string into a `SocketMessage`. Throws a `ManagedSocketError` if the deserialization fails or the deserialized shape is invalid.