relayx-js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
File without changes
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # Relay NodeJS Library
2
+ ![License](https://img.shields.io/badge/MIT-green?label=License)<br>
3
+ A powerful library for integrating real-time communication into your software stack, powered by the Relay Network.
4
+
5
+ ## Features
6
+ 1. Real-time communication made easy—connect, publish, and subscribe with minimal effort.
7
+ 2. Automatic reconnection built-in, with a 2-minute retry window for network disruptions.
8
+ 3. Message persistence during reconnection ensures no data loss when the client reconnects.
9
+
10
+ ## Installation
11
+ Install the relay library by running the command below in your terminal<br>
12
+ `npm install relay-x-js`
13
+
14
+ ## Usage
15
+ ### Prerequisites
16
+ 1. Obtain API key and Secret key
17
+ 2. Initialize the library
18
+ ```javascript
19
+ import { Realtime, CONNECTED, RECONNECT, DISCONNECTED } from "relay-x-js"
20
+
21
+ var realtime = new Realtime({
22
+ api_key: process.env.api_key,
23
+ secret: process.env.secret,
24
+ });
25
+ realtime.init();
26
+
27
+ // Initialization of topic listeners go here... (look at examples/example_chat.js for full implementation)
28
+
29
+ realtime.connect();
30
+
31
+ // Other application logic...
32
+ ```
33
+
34
+ ### Usage
35
+ 1. <b>Publish</b><br>
36
+ Send a message to a topic:<br>
37
+ ```javascript
38
+ var sent = await realtime.publish("power_telemetry", {
39
+ "voltage_V": 5,
40
+ "current_mA": 400,
41
+ "power_W": 2
42
+ });
43
+
44
+ if(sent){
45
+ console.log("Message was successfully sent to topic => power_telemetry");
46
+ }else{
47
+ console.log("Message was not sent to topic => power_telemetry");
48
+ }
49
+ ```
50
+ 2. <b>Listen</b><br>
51
+ Subscribe to a topic to receive messages:<br>
52
+ ```javascript
53
+ await realtime.on("power_telemetry", (data) => {
54
+ console.log(data);
55
+ });
56
+ ```
57
+ 3. <b>Turn Off Listener</b><br>
58
+ Unsubscribe from a topic:<br>
59
+ ```javascript
60
+ var unsubscribed = await realtime.off("power_telemetry");
61
+
62
+ if(unsubscribed){
63
+ console.log("Successfully unsubscribed from power_telemetry");
64
+ }else{
65
+ console.log("Unable to unsubscribe from power_telemetry");
66
+ }
67
+ ```
68
+ 4. <b>Valid Topic Check</b><br>
69
+ Utility function to check if a particular topic is valid
70
+ ```javascript
71
+ var isValid = realtime.isTopicValid("topic");
72
+
73
+ console.log(`Topic Valid => ${isValid}`);
74
+ ```
75
+ 5. <b>Sleep</b><br>
76
+ Utility async function to delay code execution
77
+ ```javascript
78
+ console.log("Starting code execution...");
79
+ await realtime.sleep(2000) // arg is in ms
80
+ console.log("This line executed after 2 seconds");
81
+ ```
82
+ 6. <b>Close Connection to Relay</b><br>
83
+ Manually disconnect from the Relay Network
84
+ ```javascript
85
+ // Logic here
86
+
87
+ realtime.close();
88
+ ```
89
+
90
+ ## System Events
91
+ 1. <b>CONNECTED</b><br>
92
+ This event is fired when the library connects to the Relay Network.
93
+ ```javascript
94
+ await realtime.on(CONNECTED, () => {
95
+ console.log("Connected to the Relay Network!");
96
+ });
97
+ ```
98
+
99
+ 2. <b>RECONNECT</b><br>
100
+ This event is fired when the library reconnects to the Relay Network. This is only fired when the disconnection event is not manual, i.e, disconnection due to network issues.
101
+ ```javascript
102
+ await realtime.on(RECONNECT, (status) => {
103
+ console.log(`Reconnected! => ${status}`);
104
+ });
105
+ ```
106
+ `status` can have values of `RECONNECTING` & `RECONNECTED`.
107
+
108
+ `RECONNECTING` => Reconnection attempts have begun. If `status == RECONNECTING`, the `RECONNECT` event is fired every 1 second.<br>
109
+ `RECONNECTED` => Reconnected to the Relay Network.
110
+ 3. <b>DISCONNECTED</b><br>
111
+ This event is fired when the library disconnects from the Relay Network. This includes disconnection due to network issues as well.
112
+ ```javascript
113
+ await realtime.on(DISCONNECTED, () => {
114
+ console.log("Disconnected from the Relay Network");
115
+ });
116
+ ```
117
+ 4. <b>MESSAGE_RESEND</b><br>
118
+ This event is fired when the library resends the messages upon reconnection to the Relay Network.
119
+ ```javascript
120
+ await realtime.on(MESSAGE_RESEND, (messages) => {
121
+ console.log("Offline messages may have been resent");
122
+ console.log("Messages");
123
+ console.log(messages);
124
+ });
125
+ ```
126
+ `messages` is an array of the following object,<br>
127
+ ```json
128
+ {
129
+ "topic": "<topic the message belongs to>",
130
+ "message": "<message you sent>",
131
+ "resent": "<boolean, indicating if the message was sent successully>"
132
+ }
133
+ ```
134
+
135
+ ## API Reference
136
+ 1. init()<br>
137
+ Initializes library with configuration options
138
+ 2. connect()<br>
139
+ Connects the library to the Relay Network. This is an async function.
140
+ 3. close()<br>
141
+ Disconnects the library from the Relay Network.
142
+ 3. on()<br>
143
+ Subscribes to a topic. This is an async function.
144
+ * @param {string} topic - Name of the event
145
+ * @param {function} func - Callback function to call on user thread
146
+ * @returns {boolean} - To check if topic subscription was successful
147
+ 3. off()<br>
148
+ Deletes reference to user defined event callback for a topic. This will stop listening to a topic. This is an async function.
149
+ * @param {string} topic
150
+ * @returns {boolean} - To check if topic unsubscribe was successful
151
+ 4. isTopicValid()<br>
152
+ Checks if a topic can be used to send messages to.
153
+ * @param {string} topic - Name of event
154
+ * @returns {boolean} - If topic is valid or not
155
+ 5. sleep()<br>
156
+ Pauses code execution for a user defined time. Time passed into the method is in milliseconds. This is an async function.
@@ -0,0 +1,97 @@
1
+ import { Realtime, CONNECTED, RECONNECT, DISCONNECTED, MESSAGE_RESEND } from "../realtime/realtime.js"
2
+ import * as readline from 'readline';
3
+
4
+ const rl = readline.createInterface({
5
+ input: process.stdin,
6
+ output: process.stdout
7
+ });
8
+
9
+ async function run(){
10
+ // await throttle.start(options["fois"]);
11
+
12
+ var realtime = new Realtime({
13
+ api_key: process.env.user_key,
14
+ secret: process.env.secret
15
+ });
16
+ await realtime.init({
17
+ max_retries: 2,
18
+ debug: true
19
+ });
20
+
21
+ realtime.on(CONNECTED, async () => {
22
+ console.log("[IMPL] => CONNECTED!");
23
+ });
24
+
25
+ realtime.on(RECONNECT, (status) => {
26
+ console.log(`[IMPL] RECONNECT => ${status}`)
27
+ });
28
+
29
+ realtime.on(DISCONNECTED, () => {
30
+ console.log(`[IMPL] DISONNECT`)
31
+ });
32
+
33
+ await realtime.on("hello", (data) => {
34
+ console.log("hello", data);
35
+ });
36
+
37
+ await realtime.on("hello1", (data) => {
38
+ console.log("hello1", data);
39
+ });
40
+
41
+ realtime.on(MESSAGE_RESEND, (data) => {
42
+ console.log(`[MSG RESEND] => ${data}`)
43
+ });
44
+
45
+ rl.on('line', async (input) => {
46
+ console.log(`You entered: ${input}`);
47
+
48
+ if(input == "exit"){
49
+ var output = await realtime.off("hello");
50
+ console.log(output);
51
+
52
+ realtime.close();
53
+
54
+ process.exit();
55
+ }else if(input == "history"){
56
+ var since = Date.now() - 1 * 60 * 60 * 1000; // 1 hour ago
57
+
58
+ var history = await realtime.history.getMessagesSince("hello", since, 1, 1000);
59
+ console.log(history);
60
+ }else if(input == "off"){
61
+ rl.question("topic to off(): ", async (topic) => {
62
+ await realtime.off(topic);
63
+ console.log("off() executed")
64
+ })
65
+
66
+
67
+ }else if(input == "close"){
68
+ realtime.close();
69
+ console.log("Connection closed");
70
+ }else if(input == "on"){
71
+ rl.question("topic: ", async (topic) => {
72
+ await realtime.on(topic, (data) => {
73
+ console.log(topic, data);
74
+ });
75
+ })
76
+ }else{
77
+ rl.question("topic: ", async (topic) => {
78
+ var output = await realtime.publish(topic, {
79
+ "data": input
80
+ });
81
+ })
82
+ }
83
+ });
84
+
85
+ realtime.connect();
86
+
87
+ process.on('SIGINT', async () => {
88
+ console.log('Keyboard interrupt detected (Ctrl+C). Cleaning up...');
89
+ // Perform any necessary cleanup here
90
+
91
+ // Exit the process
92
+ process.exit();
93
+ });
94
+
95
+ }
96
+
97
+ await run();
@@ -0,0 +1,46 @@
1
+ import { Realtime, CONNECTED, RECONNECT, DISCONNECTED, MESSAGE_RESEND } from "../realtime/realtime.js"
2
+
3
+ async function run(){
4
+ var realtime = new Realtime({
5
+ api_key: process.env.user_key,
6
+ secret: process.env.secret
7
+ });
8
+ await realtime.init(true, {
9
+ max_retries: 2,
10
+ debug: true
11
+ });
12
+
13
+ realtime.on(CONNECTED, async () => {
14
+ console.log("[IMPL] => CONNECTED!");
15
+
16
+ for (let angle = 0; angle <= 18000; angle++){
17
+
18
+ var value = Math.floor(Math.random() * (100 + 1))
19
+ console.log(value)
20
+
21
+ await realtime.publish("test-topic", {
22
+ "value": value,
23
+ "time": Date.now() + 2000
24
+ })
25
+
26
+ await realtime.sleep(100)
27
+ }
28
+ });
29
+
30
+ realtime.on(RECONNECT, (status) => {
31
+ console.log(`[IMPL] RECONNECT => ${status}`)
32
+ });
33
+
34
+ realtime.on(DISCONNECTED, () => {
35
+ console.log(`[IMPL] DISONNECT`)
36
+ });
37
+
38
+ realtime.on(MESSAGE_RESEND, (data) => {
39
+ console.log(`[MSG RESEND] => ${data}`)
40
+ });
41
+
42
+ realtime.connect();
43
+
44
+ }
45
+
46
+ await run();
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "relayx-js",
3
+ "version": "1.0.0",
4
+ "main": "realtime/realtime.js",
5
+ "type": "module",
6
+ "scripts": {
7
+ "test": "NODE_ENV=test node tests/test.js"
8
+ },
9
+ "keywords": ["realtime", "realtime-communication", "relay", "relay-x", "relay-x-js"],
10
+ "author": "Relay",
11
+ "license": "MIT License",
12
+ "description": "A powerful library for integrating real-time communication into your software stack, powered by the Relay Network.",
13
+ "dependencies": {
14
+ "@nats-io/jetstream": "^3.0.0-35",
15
+ "axios": "1.7.7",
16
+ "jest": "^29.7.0",
17
+ "nats": "^2.28.2"
18
+ },
19
+ "devDependencies": {
20
+ "@babel/core": "^7.26.0",
21
+ "@babel/preset-env": "^7.26.0",
22
+ "@babel/preset-react": "^7.25.9",
23
+ "babel-jest": "^29.7.0"
24
+ }
25
+ }
@@ -0,0 +1,160 @@
1
+ import axios from 'axios';
2
+
3
+ /**
4
+ * Class responsible for getting messages stored in the DB
5
+ */
6
+ export class History{
7
+
8
+ #api_key = null;
9
+ #staging = null;
10
+ #baseUrl = null;
11
+ #debug = null;
12
+
13
+ constructor(api_key){
14
+ this.#api_key = api_key;
15
+ }
16
+
17
+ init(staging, debug){
18
+ this.#staging = staging;
19
+ this.#debug = debug;
20
+
21
+ this.#setBaseUrl();
22
+ }
23
+
24
+ /**
25
+ * Get message from DB since a $timestamp
26
+ * @param {number} timestamp - unix timestamp
27
+ * @param {number} page - page number of pagination
28
+ * @param {number} limit - limit per page
29
+ * @returns - Message array
30
+ */
31
+ async getMessagesSince(topic, timestamp, page, limit){
32
+ if(topic == null || topic == undefined){
33
+ return new Error("$topic variable missing in getMessagesSince()");
34
+ }else{
35
+ if(typeof topic !== "string"){
36
+ return new Error("$topic is not a string");
37
+ }
38
+ }
39
+
40
+ if(timestamp == null || timestamp == undefined){
41
+ return new Error("$timestamp variable missing in getMessagesSince()");
42
+ }else{
43
+ if(!Number.isInteger(timestamp) && !Number.isNaN(timestamp)){
44
+ return new Error("$timestamp is either NaN or not an invalid integer");
45
+ }
46
+ }
47
+
48
+ if(page == null || page == undefined){
49
+ return new Error("$page variable missing in getMessagesSince()");
50
+ }else{
51
+ if(!Number.isInteger(page) && !Number.isNaN(page)){
52
+ return new Error("$page is either NaN or not an invalid integer");
53
+ }
54
+ }
55
+
56
+ if(limit == null || limit == undefined){
57
+ return new Error("$limit variable missing in getMessagesSince()");
58
+ }else{
59
+ if(!Number.isInteger(limit) && !Number.isNaN(limit)){
60
+ console.log("$limit is either NaN or not an invalid integer")
61
+ return new Error("$limit is either NaN or not an invalid integer");
62
+ }
63
+ }
64
+
65
+ try{
66
+ var startTime = Date.now();
67
+ var urlPart = `/history/since?topic=${topic}&timestamp=${timestamp}&page=${page}&limit=${limit}`
68
+
69
+ var response = await axios.get(this.#baseUrl + urlPart,{
70
+ headers: {
71
+ "Authorization": `Bearer ${this.#api_key}`
72
+ }
73
+ });
74
+
75
+ var data = response.data
76
+ this.#log(data);
77
+
78
+ this.#logResponseTime(startTime, urlPart);
79
+
80
+ if (data?.status === "SUCCESS"){
81
+ return data.data;
82
+ }else{
83
+ return null;
84
+ }
85
+ }catch(err){
86
+ throw Error(err.message);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Get message from DB by ID
92
+ * @param {string} id - ID of the message
93
+ * @returns - Message object
94
+ */
95
+ async getMessageById(id){
96
+ var startTime = Date.now();
97
+ var urlPart = `/history/message-by-id?id=${id}`;
98
+
99
+ if(id !== null && id !== undefined){
100
+ try{
101
+ var response = await axios.get(this.#baseUrl + urlPart,{
102
+ headers: {
103
+ "Authorization": `Bearer ${this.#api_key}`
104
+ }
105
+ });
106
+
107
+ var data = response.data
108
+ this.#log(data);
109
+
110
+ this.#logResponseTime(startTime, urlPart);
111
+
112
+ if (data?.status === "SUCCESS"){
113
+ return data.data;
114
+ }else{
115
+ return null;
116
+ }
117
+ }catch(err){
118
+ throw new Error(err.message);
119
+ }
120
+ }else{
121
+ return null;
122
+ }
123
+ }
124
+
125
+ // Utility Functions
126
+ /**
127
+ * Constructs base url based on staging flag
128
+ */
129
+ #setBaseUrl(){
130
+ if (this.#staging !== undefined || this.#staging !== null){
131
+ this.#baseUrl = this.#staging ? "http://127.0.0.1:3000" : "http://128.199.176.185:3000";
132
+ }else{
133
+ this.#baseUrl = "http://128.199.176.185:3000";
134
+ }
135
+ }
136
+
137
+ #log(msg){
138
+ if(this.#debug !== null && this.#debug !== undefined && (typeof this.#debug == "boolean")){
139
+ if(this.#debug){
140
+ console.log(msg);
141
+ }
142
+ }
143
+ }
144
+
145
+ async #logResponseTime(startTime, url){
146
+ var responseTime = Date.now() - startTime;
147
+
148
+ var data = {
149
+ "url": url,
150
+ "response_time": responseTime
151
+ }
152
+
153
+ await axios.post(this.#baseUrl + "/metrics/log", data, {
154
+ headers: {
155
+ "Authorization": `Bearer ${this.#api_key}`
156
+ }
157
+ });
158
+ }
159
+
160
+ }
File without changes