https://github.com/mitz-it/websocket-client
An abstraction over WebSocket to manage strongly typed messages
https://github.com/mitz-it/websocket-client
abstraction web-socket web-sockets websocket websockets
Last synced: 3 months ago
JSON representation
An abstraction over WebSocket to manage strongly typed messages
- Host: GitHub
- URL: https://github.com/mitz-it/websocket-client
- Owner: mitz-it
- Created: 2023-01-05T22:57:12.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-10-19T17:01:48.000Z (over 2 years ago)
- Last Synced: 2025-09-23T16:47:02.390Z (7 months ago)
- Topics: abstraction, web-socket, web-sockets, websocket, websockets
- Language: TypeScript
- Homepage:
- Size: 43.9 KB
- Stars: 0
- Watchers: 4
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Mitz IT - Web Socket Client
A higher-level abstraction of the `WebSocket` object that manages strongly-typed received messages.
## Installation
```bash
npm install @mitz-it/websocket-client@^2.0.0
```
## Usage
Import the client:
```javascript
import WebSocketClient from "@mitz-it/websocket-client";
```
Strongly typed messages can be managed using corresponding strongly typed handlers, represented by `MessageHandler`:
| Property | Type | Description |
| -------- | ----------------------------- | --------------------------------------- |
| key | `string` | Unique identifier for the message type |
| callback | `OnMessageCallback` | Function invoked with the typed message |
| assert | `TypeAssertion` | Asserts if a message matches the type |
Define your handler by implementing the `MessageHandler` structure:
```typescript
interface CustomMessage {
foo: string;
bar: int;
}
const callback = (message: CustomMessage): void => {
console.log(message);
};
const assert = (message: any): message is CustomMessage => {
return "foo" in message && "bar" in message;
};
const handler = {
key: "custom-message-key",
callback: callback,
assert: assert,
};
```
Create an instance of the `WebSocketClient` object, and register the handler:
```typescript
const client = new WebSocketClient("wss://some-domain.com");
client.addMessageHandler(handler);
client.connect(
() => console.log("Connected!"),
(e, reconnect) => {
if (e.code === YOUR_SERVER_CODE_FOR_MAX_TIME_LIMIT) {
console.log("Reconnecting...");
reconnect();
}
}
);
```
Publishing a message:
```typescript
client.publish({ foo: "string", bar: 1 });
```
Safe publishing:
```typescript
if (client.connected())
client.publish({ foo: "string", bar: 1 });
```
Remove a handler:
```typescript
client.removeMessageHandler("custom-message-key");
```
Clear all handlers:
```typescript
client.clearMessageHandlers();
```