ws-realtime-client
v1.0.1-alpha.7
Published
Lightweight, simple-to-use library for streaming realtime data to clients via WebSockets. Client Version.
Downloads
7
Readme
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
WebSocket Connection Functions
connect(url: string): void
- Description: Establishes a WebSocket connection to the provided URL.
- Parameters:
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();
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:
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:
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);
});
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:
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);
Event Listeners
onStateChange(callback: Function): void
- Description: Registers a callback function that will be called whenever the state (data) changes.
- Parameters:
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:
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:
event
: The name of the WebSocket event (e.g.,'open'
,'close'
,'message'
,'error'
).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:
event
: The name of the WebSocket event (e.g.,'open'
,'close'
,'message'
,'error'
).callback
: The function to remove.
- Usage Example:
const onOpenHandler = () => {
console.log('WebSocket connection opened');
};
onWebSocketEvent('open', onOpenHandler);
offWebSocketEvent('open', onOpenHandler);
Conventions
- Message Structure: The internal message structure follows the
Initial
,Create
,Update
, andDelete
(ICUD) model. The message contains details about the changes in the datamodel, and this is handled internally by the library. - 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.
- Event Handling: Both WebSocket and state changes are event-driven, providing a reactive pattern for real-time updates.