ws-realtime-client

1.0.1-alpha.7 • Public • Published

ws-realtime-client Library

Overview

ws-realtime-client is a WebSocket-based library designed to connect to the ws-realtime backend API and provide real-time updates of subscribed datamodels. The library is lightweight and easy to integrate into any frontend project (e.g., React, Preact). It decouples all WebSocket logic from UI, making it reusable across different projects and frameworks.

This package provides utilities for:

  • Connecting/disconnecting to/from a WebSocket server.
  • Subscribing and unsubscribing from datamodels.
  • Managing and accessing real-time datamodel data.
  • Listening to WebSocket and state change events.

The data state is always up-to-date with real-time streaming from the backend WebSocket server. This allows frontend applications to dynamically reflect any changes without additional polling.

Installation

To install the library in your project, use:

npm install ws-realtime-client

Basic Usage Example

Here’s an example of how to use the ws-realtime-client package in your project:

import {
  connect,
  disconnect,
  subscribe,
  unsubscribe,
  listDatamodels,
  getData,
  getDatamodelData,
  getSubscribedDatamodels,
  getClientUUID,
  onStateChange,
  onWebSocketEvent,
  offStateChange,
  offWebSocketEvent,
} from 'ws-realtime-client';

// Connect to WebSocket server
connect('ws://localhost:3002/realtime');

// Subscribe to a datamodel
subscribe('Chargers').then(() => {
  console.log('Subscribed to Chargers datamodel');
});

// Get data for all subscribed datamodels
const allData = getData();
console.log(allData);

// Get data for a specific datamodel
const chargersData = getDatamodelData('Chargers');
console.log(chargersData);

// List available datamodels from the server
listDatamodels().then((models) => {
  console.log('Available datamodels:', models);
});

// Listen to state changes (e.g., when new data arrives)
onStateChange(() => {
  const updatedData = getData();
  console.log('Data updated:', updatedData);
});

// Listen to WebSocket events (e.g., connection open, close)
onWebSocketEvent('open', () => {
  console.log('WebSocket connection opened.');
});

// Unsubscribe from a datamodel
unsubscribe('Chargers').then(() => {
  console.log('Unsubscribed from Chargers datamodel');
});

// Disconnect from WebSocket server
disconnect();

Public API Documentation

  1. WebSocket Connection Functions

connect(url: string): void

  • Description: Establishes a WebSocket connection to the provided URL.
  • Parameters:
  1. url: The WebSocket server URL (e.g., 'ws://localhost:3002/realtime').
  • Usage Example:
   connect('ws://localhost:3002/realtime');

disconnect(): void

  • Description: Disconnects from the currently connected WebSocket server.
  • Usage Example:
   disconnect();
  1. Subscription Functions

subscribe(datamodel: string): Promise<boolean>

  • Description: Subscribes to a specific datamodel. The backend will start sending real-time updates for this datamodel.
  • Parameters:
  1. datamodel: The name of the datamodel to subscribe to (e.g., 'Chargers').
  • Returns: A promise that resolves when the subscription is successful.
  • Usage Example:
   subscribe('Chargers').then(() => {
   console.log('Subscribed to Chargers');
   }).catch((err) => {
   console.error('Failed to subscribe:', err);
   });

unsubscribe(datamodel: string): Promise<boolean>

  • Description: Unsubscribes from a specific datamodel. The backend will stop sending real-time updates for this datamodel.
  • Parameters:
  1. datamodel: The name of the datamodel to unsubscribe from (e.g., 'Chargers').
  • Returns: A promise that resolves when the unsubscription is successful.
  • Usage Example:
   unsubscribe('Chargers').then(() => {
   console.log('Unsubscribed from Chargers');
   }).catch((err) => {
   console.error('Failed to unsubscribe:', err);
   });

listDatamodels(): Promise<string[]>

  • Description: Retrieves a list of all available datamodels from the WebSocket server.
  • Returns: A promise that resolves with an array of datamodel names.
  • Usage Example:
   listDatamodels().then((models) => {
   console.log('Available datamodels:', models);
   }).catch((err) => {
   console.error('Failed to list datamodels:', err);
   });
  1. State Accessor Functions

getData(): object

  • Description: Returns the full set of data from all subscribed datamodels.
  • Returns: An object where each key is a datamodel name, and the value is an object containing all the datamodel entries.
  • Usage Example:
   const allData = getData();
   console.log(allData);

getDatamodelData(datamodel: string): object

  • Description: Retrieves the full set of data for a specific subscribed datamodel.
  • Parameters:
  1. datamodel: The name of the datamodel (e.g., 'Chargers').
  • Returns: An object containing all entries for the datamodel.
  • Usage Example:
   const chargersData = getDatamodelData('Chargers');
   console.log(chargersData);

getSubscribedDatamodels(): string[]

  • Description: Returns a list of all datamodels that the client is currently subscribed to.
  • Returns: An array of datamodel names.
  • Usage Example:
   const subscribedModels = getSubscribedDatamodels();
   console.log(subscribedModels);

getClientUUID(): string

  • Description: Returns the UUID of the current client connected to the WebSocket server.
  • Returns: A string representing the client's UUID.
  • Usage Example:
   const uuid = getClientUUID();
   console.log('Client UUID:', uuid);
  1. Event Listeners

onStateChange(callback: Function): void

  • Description: Registers a callback function that will be called whenever the state (data) changes.
  • Parameters:
  1. callback: A function that will be called when state changes (e.g., new data arrives).
  • Usage Example:
   onStateChange(() => {
   console.log('State has changed');
   const updatedData = getData();
   console.log('Updated data:', updatedData);
   });

offStateChange(callback: Function): void

  • Description: Removes a previously registered state change callback.
  • Parameters:
  1. callback: The callback function to remove.
  • Usage Example:
   const stateChangeHandler = () => {
   console.log('State has changed');
   };

   onStateChange(stateChangeHandler);
   offStateChange(stateChangeHandler);

onWebSocketEvent(event: string, callback: Function): void

  • Description: Registers a callback function for WebSocket events (e.g., open, close, message, error).
  • Parameters:
  1. event: The name of the WebSocket event (e.g., 'open', 'close', 'message', 'error').
  2. callback: The function to call when the event occurs.
  • Usage Example:
   onWebSocketEvent('open', () => {
   console.log('WebSocket connection opened');
   });

   onWebSocketEvent('close', () => {
   console.log('WebSocket connection closed');
   });

offWebSocketEvent(event: string, callback: Function): void

  • Description: Removes a previously registered WebSocket event listener.
  • Parameters:
  1. event: The name of the WebSocket event (e.g., 'open', 'close', 'message', 'error').
  2. callback: The function to remove.
  • Usage Example:
   const onOpenHandler = () => {
   console.log('WebSocket connection opened');
   };

   onWebSocketEvent('open', onOpenHandler);
   offWebSocketEvent('open', onOpenHandler);

Conventions

  1. Message Structure: The internal message structure follows the Initial, Create, Update, and Delete (ICUD) model. The message contains details about the changes in the datamodel, and this is handled internally by the library.
  2. State Management: The state manager is encapsulated and only exposed through getter functions. Developers cannot mutate the state directly, ensuring that the data remains consistent with the server.
  3. Event Handling: Both WebSocket and state changes are event-driven, providing a reactive pattern for real-time updates.

Readme

Keywords

none

Package Sidebar

Install

npm i ws-realtime-client

Weekly Downloads

0

Version

1.0.1-alpha.7

License

MIT

Unpacked Size

17.8 kB

Total Files

7

Last publish

Collaborators

  • bradleyfischer