2.0.0 • Published 7 months ago

@mitz-it/websocket-client v2.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
7 months ago

Mitz IT - Web Socket Client

A higher-level abstraction of the WebSocket object that manages strongly-typed received messages.

Installation

npm install @mitz-it/websocket-client@^2.0.0

Usage

Import the client:

import WebSocketClient from "@mitz-it/websocket-client";

Strongly typed messages can be managed using corresponding strongly typed handlers, represented by MessageHandler<TMessage>:

PropertyTypeDescription
keystringUnique identifier for the message type
callbackOnMessageCallback<TMessage>Function invoked with the typed message
assertTypeAssertion<TMessage>Asserts if a message matches the type

Define your handler by implementing the MessageHandler<TMessage> structure:

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:

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:

client.publish<CustomMessage>({ foo: "string", bar: 1 });

Safe publishing:

if (client.connected())
  client.publish<CustomMessage>({ foo: "string", bar: 1 });

Remove a handler:

client.removeMessageHandler("custom-message-key");

Clear all handlers:

client.clearMessageHandlers();
1.7.0

8 months ago

1.6.0

8 months ago

2.0.0

7 months ago

1.5.0

1 year ago

1.4.1

1 year ago

1.4.0

1 year ago

1.3.0

1 year ago

1.2.3

1 year ago

1.2.2

1 year ago

1.2.1

1 year ago

1.2.0

1 year ago

1.1.0

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago