Update readme

This commit is contained in:
Endeavorance 2025-05-03 13:15:03 -04:00
parent faf0254ffa
commit 466fa26cfd

View file

@ -4,9 +4,7 @@ Lightweight reconnecting websocket interface
## ManagedSocket ## ManagedSocket
A self-reconnecting wrapped WebSocket with built-in heartbeats ### `new ManagedSocket(url: string, handlers?: EventHandlers): ManagedSocket`
### `new ManagedSocket(url: string): ManagedSocket`
Create a new `ManagedSocket` instance and connect to the provided URL via WebSocket. Create a new `ManagedSocket` instance and connect to the provided URL via WebSocket.
@ -15,10 +13,14 @@ The provided URL should use the `ws://` or `wss://` protocol.
```typescript ```typescript
import { ManagedSocket } from "@endeavorance/socket"; import { ManagedSocket } from "@endeavorance/socket";
const mySocket = new ManagedSocket("wss://socket.my-server.web"); const mySocket = new ManagedSocket("wss://socket.my-server.web", {
onConnected: () => {},
onMessage: (data: unknown) => {},
onError: (error: SocketError) => {},
onDisconnected: ({wasClean, code, reason}) => {},
});
``` ```
### `.send<T>(data: T)` ### `.send<T>(data: T)`
Sends the provided data over the socket. Sends the provided data over the socket.
@ -36,9 +38,9 @@ mySocket.send({
}); });
``` ```
### `.onMessage(handler: SocketDataHandler)` ### `.onMessage: SocketDataHandler`
Provide a function to invoke whenever the socket receives a message meant to be handled by your application. 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`. This handler will be passed the blob of data contained within the message, which is typed as `unknown`.
@ -50,10 +52,10 @@ const handler = (data: unknown) => {
} }
const mySocket = new ManagedSocket("..."); const mySocket = new ManagedSocket("...");
mySocket.onMessage(handler); mySocket.onMessage = handler;
``` ```
### `.onError(handler: SocketErrorHandler)` ### `.onError: SocketErrorHandler`
Provide a function to invoke when the socket encounters a non-catastrophic error. Provide a function to invoke when the socket encounters a non-catastrophic error.
@ -67,80 +69,38 @@ const errorHandler = (error: ManagedSocketError) => {
} }
const mySocket = new ManagedSocket("..."); const mySocket = new ManagedSocket("...");
mySocket.onError(handler); mySocket.onError = errorHandler;
``` ```
### `.onCatastrophicError(handler: SocketCatastrophicErrorHandler)` ### `.onConnected: SocketOpenHandler`
Provide a function to invoke when the socket is terminated with a non-reconnect code. When this handler is invoked, it means the socket connection is terminated and unable to be recovered automatically. Your handler will be passed the `SocketDisconnectCode` associated with the connection termination.
You may still attempt to manuall reconnect using the `.reconnect()` method, but it will not be automatic.
```typescript
const bigOops = (code) => {
console.error(`Welp, we're done here. Closed with code: ${code}`);
}
const mySocket = new ManagedSocket("...");
mySocket.onCatastrophicError(bigOops);
```
### `.onOpen(SocketOpenHandler)`
Provide a function to be invoked when the connection is opened. Provide a function to be invoked when the connection is opened.
No arguments are provided to this handler. No arguments are provided to this handler.
### `.onClose(SocketCloseHandler)` ### `.onDisconnected: SocketCloseHandler`
Provide a function to be invoked when the connection closes cleanly. Provide a function to be invoked when the connection closes cleanly.
No arguments are provided to this handler. No arguments are provided to this handler.
### `.reconnect()`
Attempts to reconnect the socket using an exponential backoff algorithm. Each failed connection attempt will wait a bit longer before the next try.
### `.close()` ### `.close()`
Safely close the socket connection. Safely close the socket connection.
## `SocketSpeak` ## `Utilities`
`SocketSpeak` is a set of utilities for working with the `ManagedSocket` data interface. It is lower-level and meant primarily for writing servers.
All methods are defined on the `SocketSpeak` object, exported by the library. ### `wrap<T>(data: T): SocketDataMessage`
```typescript Wraps the provided data in a shape to be serialized and sent over the socket.
import { SocketSpeak } from "@endeavorance/socket"
```
### `createDataMessage<T>(data: T): SocketDataMessage` ### unwrap<T>(message: SocketDataMessage): T
Wraps the provided data in a well formatted message ready to serialize and send over the socket. Unwraps the provided `SocketDataMessage` to extract the data contained within.
A `SocketDataMessage` is used for sending application data over the socket.
### `createHeartbeatMessage(): SocketHeartbeatMessage`
Creates a well formatted heartbeat message to serialize and send over the socket.
A `SocketHeartbeatMessage` is used internally to keep the connection alive and carries a data payload of the current timestamp as a string.
### `serialize(message: SocketMessage): SerializedSocketMessage`
Serialize any `SocketMessage`. Returns a `SerializedSocketMessage` which is a branded `string` type for type safety.
### `deserialize(data: string): SocketMessage` ### `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. Attempts to deserialize the provided string into a `SocketMessage`. Throws a `ManagedSocketError` if the deserialization fails or the deserialized shape is invalid.
Note: This is not to deserialize your application data messages. The managed socket handles wrapping and unwrapping messages before handing the payload to your application.
### `prepare<T>(data: T)`
Shorthand for `serialize(createDataMessage(data))
### `isCatastrophicCloseCode(code: SocketCloseCode)`
Returns `true` if the provided `SocketCloseCode` is a non-reconnect close code, or `false` otherwise.