Skip to main content

Web Sockets (TypeScript)

synternet-pubsub-ws is a TypeScript library for the Synternet Data Layer project that allows you to subscribe to existing data streams or publish new ones from frontend applications. This library is built on top of the NATS messaging system with WebSocket support, providing a convenient way to integrate your frontend TypeScript applications with the Synternet Data Layer platform.

Installation

To use the WebSocket SDK for Data Layer in your project, you can include the provided JavaScript file in your HTML:

<script src="path/to/pubsub-ws.js"></script>

Alternatively, you can install it using npm:

npm install synternet-pubsub-ws

Getting Started

Before you begin using the WebSocket SDK, make sure you have the necessary credentials and access tokens from the Synternet Developer Portalplatform. These credentials will allow you to connect to the Data Layer and subscribe to or publish data streams.

Example

For detailed usage examples, please refer to the examples directory in the repository. These examples cover various scenarios and demonstrate how to utilize the SDK's features effectively.

The preferred method of authentication is using an access token from the developer portal.

import { subscribe, Message, NatsConfig, createAppJwt } from 'pubsub-ws';

const natsWsUrl = 'wss://url.com:443';
const accessToken = 'SAAGNJOZTRPYYXG2NJX3ZNGXYUSDYX2BWO447W3SHG6XQ7U66RWHQ3JUXM';
const exampleSubscribeSubject = 'example.sub.subject';

var config: NatsConfig;

async function printData(message: Message) {
console.log('Received message on', exampleSubscribeSubject, 'subject');
}

const onMessages = async (messages: Message[]) => {
messages
.filter((message) => message.subject === exampleSubscribeSubject)
.forEach((message) => printData(message));
};

const onError = (text: string, error: Error) => {
console.error(text, error);
};

async function main() {
config = { url: natsWsUrl }
const { userSeed: seed, jwt } = createAppJwt(accessToken);

await subscribe({
onMessages,
onError,
jwt: jwt,
nkey: seed,
config: config,
subject: exampleSubscribeSubject
});
console.log('Connected to NATS server.');
}

main();

Contributing

We welcome contributions from the community! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository. We appreciate your feedback and collaboration in making this SDK even better.

Support

If you encounter any difficulties or have questions regarding the TypeScript SDK for Data Layer, please reach out to our support team at Discord #developers-chat. We are here to assist you and ensure a smooth experience with our SDK.

We hope this documentation provides you with a comprehensive understanding of the TypeScript SDK for the Data Layer. Happy coding with real-time data streams and enjoy the power of the Data Layer in your TypeScript applications!