jolt-js-api 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/LICENSE +21 -0
- package/README.md +201 -0
- package/examples/advanced-usage.js +113 -0
- package/examples/multiple-clients.js +55 -0
- package/examples/simple-chat.js +68 -0
- package/package.json +33 -0
- package/src/JoltClient.js +135 -0
- package/test/client.test.js +128 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 DevArqf
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# Jolt JavaScript API
|
|
2
|
+
|
|
3
|
+
A JavaScript & Node.js client for the [Jolt](https://github.com/Jolt-Database/Jolt) in-memory messaging broker.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
✅ Native Jolt broker protocol support
|
|
8
|
+
✅ Event-driven architecture (EventEmitter)
|
|
9
|
+
✅ Promise-based API available
|
|
10
|
+
✅ Simple pub/sub messaging
|
|
11
|
+
✅ No external dependencies (Node.js core only)
|
|
12
|
+
✅ TypeScript definitions included
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install jolt-js-api
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Or from source:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
git clone https://github.com/DevArqf/jolt-js-api.git
|
|
24
|
+
cd jolt-js-api
|
|
25
|
+
npm install
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```javascript
|
|
31
|
+
const JoltClient = require('jolt-js-api');
|
|
32
|
+
|
|
33
|
+
// Create client
|
|
34
|
+
const client = new JoltClient({
|
|
35
|
+
host: '127.0.0.1',
|
|
36
|
+
port: 8080
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// Set up event handlers
|
|
40
|
+
client.on('connected', () => console.log('Connected'));
|
|
41
|
+
client.on('ok', () => console.log('✓ OK'));
|
|
42
|
+
client.on('error', (error) => console.log('✗ Error:', error));
|
|
43
|
+
client.on('message', (topic, data) => console.log(`[${topic}] ${data}`));
|
|
44
|
+
client.on('disconnected', () => console.log('Disconnected'));
|
|
45
|
+
|
|
46
|
+
// Connect and use
|
|
47
|
+
async function main() {
|
|
48
|
+
await client.connect();
|
|
49
|
+
|
|
50
|
+
client.subscribe('chat.general');
|
|
51
|
+
client.publish('chat.general', 'Hello, Jolt!');
|
|
52
|
+
client.ping();
|
|
53
|
+
|
|
54
|
+
// Keep running...
|
|
55
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
56
|
+
|
|
57
|
+
client.close();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
main();
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## API Reference
|
|
64
|
+
|
|
65
|
+
### Constructor
|
|
66
|
+
|
|
67
|
+
```javascript
|
|
68
|
+
const client = new JoltClient(config);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Config Options:**
|
|
72
|
+
- `host` (string): Broker host (default: '127.0.0.1')
|
|
73
|
+
- `port` (number): Broker port (default: 8080)
|
|
74
|
+
|
|
75
|
+
### Methods
|
|
76
|
+
|
|
77
|
+
#### Connection
|
|
78
|
+
- `connect()` → Promise<void> - Connect to broker
|
|
79
|
+
- `close()` → void - Close connection
|
|
80
|
+
- `isConnected()` → boolean - Check connection status
|
|
81
|
+
|
|
82
|
+
#### Operations
|
|
83
|
+
- `auth(username, password)` → void - Authenticate
|
|
84
|
+
- `subscribe(topic)` → void - Subscribe to topic
|
|
85
|
+
- `unsubscribe(topic)` → void - Unsubscribe from topic
|
|
86
|
+
- `publish(topic, data)` → void - Publish message
|
|
87
|
+
- `ping()` → void - Send ping
|
|
88
|
+
|
|
89
|
+
### Events
|
|
90
|
+
|
|
91
|
+
```javascript
|
|
92
|
+
client.on('connected', () => {})
|
|
93
|
+
client.on('ok', (rawLine) => {})
|
|
94
|
+
client.on('error', (errorMsg, rawLine) => {})
|
|
95
|
+
client.on('message', (topic, data, rawLine) => {})
|
|
96
|
+
client.on('disconnected', () => {})
|
|
97
|
+
client.on('socketError', (err) => {})
|
|
98
|
+
client.on('parseError', (err, line) => {})
|
|
99
|
+
client.on('unknown', (data, line) => {})
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Examples
|
|
103
|
+
|
|
104
|
+
### Simple Chat
|
|
105
|
+
|
|
106
|
+
```javascript
|
|
107
|
+
const JoltClient = require('jolt-js-api');
|
|
108
|
+
|
|
109
|
+
const client = new JoltClient();
|
|
110
|
+
|
|
111
|
+
client.on('message', (topic, data) => {
|
|
112
|
+
console.log(`[${topic}] ${data}`);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
await client.connect();
|
|
116
|
+
client.subscribe('chat.room1');
|
|
117
|
+
client.publish('chat.room1', 'Hello everyone!');
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Multiple Topics
|
|
121
|
+
|
|
122
|
+
```javascript
|
|
123
|
+
const topics = ['news', 'sports', 'weather'];
|
|
124
|
+
|
|
125
|
+
// Subscribe to all
|
|
126
|
+
topics.forEach(topic => client.subscribe(topic));
|
|
127
|
+
|
|
128
|
+
// Publish to each
|
|
129
|
+
client.publish('news', 'Breaking news!');
|
|
130
|
+
client.publish('sports', 'Score: 3-2');
|
|
131
|
+
client.publish('weather', 'Sunny, 25°C');
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Promise-Based Operations
|
|
135
|
+
|
|
136
|
+
```javascript
|
|
137
|
+
const JoltClientWrapper = require('./examples/advanced-usage');
|
|
138
|
+
|
|
139
|
+
const client = new JoltClientWrapper({ host: '127.0.0.1', port: 8080 });
|
|
140
|
+
|
|
141
|
+
await client.connect();
|
|
142
|
+
await client.subscribeAsync('chat.general');
|
|
143
|
+
await client.publishAsync('chat.general', 'Hello!');
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Error Handling
|
|
147
|
+
|
|
148
|
+
```javascript
|
|
149
|
+
client.on('error', (error) => {
|
|
150
|
+
if (error.includes('auth')) {
|
|
151
|
+
console.error('Authentication failed!');
|
|
152
|
+
} else if (error.includes('unknown_topic')) {
|
|
153
|
+
console.error('Topic does not exist!');
|
|
154
|
+
} else {
|
|
155
|
+
console.error('Error:', error);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
client.on('socketError', (err) => {
|
|
160
|
+
console.error('Socket error:', err);
|
|
161
|
+
// Implement reconnection logic
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Testing
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
# Run tests (broker must be running)
|
|
169
|
+
npm test
|
|
170
|
+
|
|
171
|
+
# Watch mode
|
|
172
|
+
npm run test:watch
|
|
173
|
+
|
|
174
|
+
# Run examples
|
|
175
|
+
npm run example
|
|
176
|
+
npm run example:advanced
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Protocol
|
|
180
|
+
|
|
181
|
+
Jolt uses NDJSON (newline-delimited JSON) over TCP:
|
|
182
|
+
|
|
183
|
+
### Commands
|
|
184
|
+
```json
|
|
185
|
+
{"op": "auth", "user": "username", "pass": "password"}
|
|
186
|
+
{"op": "sub", "topic": "channel"}
|
|
187
|
+
{"op": "unsub", "topic": "channel"}
|
|
188
|
+
{"op": "pub", "topic": "channel", "data": "message"}
|
|
189
|
+
{"op": "ping"}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Responses
|
|
193
|
+
```json
|
|
194
|
+
{"ok": true}
|
|
195
|
+
{"ok": false, "error": "error_message"}
|
|
196
|
+
{"topic": "channel", "data": "message"}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## License
|
|
200
|
+
|
|
201
|
+
MIT License - see LICENSE file for details
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const JoltClient = require('../src/JoltClient');
|
|
2
|
+
|
|
3
|
+
class JoltClientWrapper {
|
|
4
|
+
constructor(config) {
|
|
5
|
+
this.client = new JoltClient(config);
|
|
6
|
+
this.responseHandlers = new Map();
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async connect() {
|
|
10
|
+
return this.client.connect();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async subscribeAsync(topic) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const timeout = setTimeout(() => {
|
|
16
|
+
reject(new Error('Subscription timeout'));
|
|
17
|
+
}, 5000);
|
|
18
|
+
|
|
19
|
+
const okHandler = () => {
|
|
20
|
+
clearTimeout(timeout);
|
|
21
|
+
this.client.off('ok', okHandler);
|
|
22
|
+
this.client.off('error', errorHandler);
|
|
23
|
+
resolve();
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const errorHandler = (error) => {
|
|
27
|
+
clearTimeout(timeout);
|
|
28
|
+
this.client.off('ok', okHandler);
|
|
29
|
+
this.client.off('error', errorHandler);
|
|
30
|
+
reject(new Error(error));
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
this.client.once('ok', okHandler);
|
|
34
|
+
this.client.once('error', errorHandler);
|
|
35
|
+
this.client.subscribe(topic);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async publishAsync(topic, data) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const timeout = setTimeout(() => {
|
|
42
|
+
reject(new Error('Publish timeout'));
|
|
43
|
+
}, 5000);
|
|
44
|
+
|
|
45
|
+
const okHandler = () => {
|
|
46
|
+
clearTimeout(timeout);
|
|
47
|
+
this.client.off('ok', okHandler);
|
|
48
|
+
this.client.off('error', errorHandler);
|
|
49
|
+
resolve();
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const errorHandler = (error) => {
|
|
53
|
+
clearTimeout(timeout);
|
|
54
|
+
this.client.off('ok', okHandler);
|
|
55
|
+
this.client.off('error', errorHandler);
|
|
56
|
+
reject(new Error(error));
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
this.client.once('ok', okHandler);
|
|
60
|
+
this.client.once('error', errorHandler);
|
|
61
|
+
this.client.publish(topic, data);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
on(event, handler) {
|
|
66
|
+
this.client.on(event, handler);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
close() {
|
|
70
|
+
this.client.close();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function advancedExample() {
|
|
75
|
+
const client = new JoltClientWrapper({
|
|
76
|
+
host: '127.0.0.1',
|
|
77
|
+
port: 8080
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
client.on('message', (topic, data) => {
|
|
81
|
+
console.log(`📩 [${topic}] ${data}`);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
console.log('Connecting...');
|
|
86
|
+
await client.connect();
|
|
87
|
+
console.log('✓ Connected');
|
|
88
|
+
|
|
89
|
+
console.log('Subscribing to topics...');
|
|
90
|
+
await client.subscribeAsync('news');
|
|
91
|
+
await client.subscribeAsync('sports');
|
|
92
|
+
console.log('✓ Subscribed');
|
|
93
|
+
|
|
94
|
+
console.log('Publishing messages...');
|
|
95
|
+
await client.publishAsync('news', 'Breaking: Node.js API released!');
|
|
96
|
+
await client.publishAsync('sports', 'Score: 3-2');
|
|
97
|
+
console.log('✓ Published');
|
|
98
|
+
|
|
99
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
100
|
+
|
|
101
|
+
client.close();
|
|
102
|
+
console.log('✓ Closed');
|
|
103
|
+
} catch (err) {
|
|
104
|
+
console.error('Error:', err.message);
|
|
105
|
+
client.close();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (require.main === module) {
|
|
110
|
+
advancedExample();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = JoltClientWrapper;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const JoltClient = require('../src/JoltClient');
|
|
2
|
+
|
|
3
|
+
async function multipleClientsExample() {
|
|
4
|
+
console.log('Creating two clients...\n');
|
|
5
|
+
|
|
6
|
+
const client1 = new JoltClient({ host: '127.0.0.1', port: 8080 });
|
|
7
|
+
client1.on('message', (topic, data) => {
|
|
8
|
+
console.log(`[Client 1] 📩 [${topic}] ${data}`);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const client2 = new JoltClient({ host: '127.0.0.1', port: 8080 });
|
|
12
|
+
client2.on('message', (topic, data) => {
|
|
13
|
+
console.log(`[Client 2] 📩 [${topic}] ${data}`);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
console.log('Connecting clients...');
|
|
18
|
+
await client1.connect();
|
|
19
|
+
await client2.connect();
|
|
20
|
+
console.log('✓ Both clients connected\n');
|
|
21
|
+
|
|
22
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
23
|
+
|
|
24
|
+
console.log('Subscribing to shared.channel...');
|
|
25
|
+
client1.subscribe('shared.channel');
|
|
26
|
+
client2.subscribe('shared.channel');
|
|
27
|
+
|
|
28
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
29
|
+
|
|
30
|
+
console.log('\nClient 1 publishing...');
|
|
31
|
+
client1.publish('shared.channel', 'Hello from Client 1!');
|
|
32
|
+
|
|
33
|
+
await new Promise(resolve => setTimeout(resolve, 500));
|
|
34
|
+
|
|
35
|
+
console.log('Client 2 publishing...');
|
|
36
|
+
client2.publish('shared.channel', 'Hello from Client 2!');
|
|
37
|
+
|
|
38
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
39
|
+
|
|
40
|
+
console.log('\nClosing connections...');
|
|
41
|
+
client1.close();
|
|
42
|
+
client2.close();
|
|
43
|
+
console.log('✓ Done');
|
|
44
|
+
} catch (err) {
|
|
45
|
+
console.error('Error:', err);
|
|
46
|
+
client1.close();
|
|
47
|
+
client2.close();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (require.main === module) {
|
|
52
|
+
multipleClientsExample();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = multipleClientsExample;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const JoltClient = require('../src/JoltClient');
|
|
2
|
+
|
|
3
|
+
async function main() {
|
|
4
|
+
const client = new JoltClient({
|
|
5
|
+
host: '127.0.0.1',
|
|
6
|
+
port: 8080
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
client.on('connected', () => {
|
|
10
|
+
console.log('✓ Connected to Jolt broker');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
client.on('ok', () => {
|
|
14
|
+
console.log('✓ OK');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
client.on('error', (error) => {
|
|
18
|
+
console.log(`✗ Error: ${error}`);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
client.on('message', (topic, data) => {
|
|
22
|
+
console.log(`📩 [${topic}] ${data}`);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
client.on('disconnected', () => {
|
|
26
|
+
console.log('👋 Disconnected');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
console.log('Connecting...');
|
|
31
|
+
await client.connect();
|
|
32
|
+
|
|
33
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
34
|
+
|
|
35
|
+
// AUTHENTICATE FIRST (required when security is enabled)
|
|
36
|
+
console.log('Authenticating...');
|
|
37
|
+
client.auth('admin', 'joltadmin');
|
|
38
|
+
|
|
39
|
+
await new Promise(resolve => setTimeout(resolve, 300));
|
|
40
|
+
|
|
41
|
+
console.log('Subscribing to chat.general...');
|
|
42
|
+
client.subscribe('chat.general');
|
|
43
|
+
|
|
44
|
+
await new Promise(resolve => setTimeout(resolve, 300));
|
|
45
|
+
|
|
46
|
+
console.log('Publishing messages...');
|
|
47
|
+
client.publish('chat.general', 'Hello from Node.js!');
|
|
48
|
+
client.publish('chat.general', 'Authentication working!');
|
|
49
|
+
|
|
50
|
+
await new Promise(resolve => setTimeout(resolve, 300));
|
|
51
|
+
|
|
52
|
+
console.log('Sending ping...');
|
|
53
|
+
client.ping();
|
|
54
|
+
|
|
55
|
+
console.log('\nListening for messages...\n');
|
|
56
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
57
|
+
|
|
58
|
+
console.log('\nClosing connection...');
|
|
59
|
+
client.close();
|
|
60
|
+
|
|
61
|
+
console.log('✓ Done!');
|
|
62
|
+
} catch (err) {
|
|
63
|
+
console.error('Error:', err);
|
|
64
|
+
client.close();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
main().catch(console.error);
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "jolt-js-api",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "JavaScript & Node.js client for the Jolt in-memory messaging broker",
|
|
5
|
+
"main": "src/JoltClient.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "jest",
|
|
8
|
+
"test:watch": "jest --watch",
|
|
9
|
+
"example": "node examples/simple-chat.js",
|
|
10
|
+
"example:advanced": "node examples/advanced-usage.js"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"jolt",
|
|
14
|
+
"messaging",
|
|
15
|
+
"broker",
|
|
16
|
+
"pubsub",
|
|
17
|
+
"real-time",
|
|
18
|
+
"tcp",
|
|
19
|
+
"ndjson"
|
|
20
|
+
],
|
|
21
|
+
"author": "DevArqf",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/DevArqf/jolt-js-api"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"jest": "^29.0.0"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=14.0.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
const net = require('net');
|
|
2
|
+
const EventEmitter = require('events');
|
|
3
|
+
|
|
4
|
+
class JoltClient extends EventEmitter {
|
|
5
|
+
constructor(config = {}) {
|
|
6
|
+
super();
|
|
7
|
+
this.host = config.host || '127.0.0.1';
|
|
8
|
+
this.port = config.port || 8080;
|
|
9
|
+
this.socket = null;
|
|
10
|
+
this.connected = false;
|
|
11
|
+
this.buffer = '';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
connect() {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
this.socket = net.createConnection({
|
|
17
|
+
host: this.host,
|
|
18
|
+
port: this.port
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
this.socket.on('connect', () => {
|
|
22
|
+
this.connected = true;
|
|
23
|
+
this.emit('connected');
|
|
24
|
+
resolve();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
this.socket.on('data', (chunk) => {
|
|
28
|
+
this._handleData(chunk);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
this.socket.on('error', (err) => {
|
|
32
|
+
this.connected = false;
|
|
33
|
+
this.emit('socketError', err);
|
|
34
|
+
reject(err);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
this.socket.on('close', () => {
|
|
38
|
+
this.connected = false;
|
|
39
|
+
this.emit('disconnected');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
this.socket.on('end', () => {
|
|
43
|
+
this.connected = false;
|
|
44
|
+
this.emit('disconnected');
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Authenticate with the broker (REQUIRED if security is enabled)
|
|
51
|
+
* Protocol: {"op": "auth", "user": "...", "pass": "..."}
|
|
52
|
+
*/
|
|
53
|
+
auth(username, password) {
|
|
54
|
+
this._send({ op: 'auth', user: username, pass: password });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
subscribe(topic) {
|
|
58
|
+
this._send({ op: 'sub', topic });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
unsubscribe(topic) {
|
|
62
|
+
this._send({ op: 'unsub', topic });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
publish(topic, data) {
|
|
66
|
+
this._send({ op: 'pub', topic, data });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
ping() {
|
|
70
|
+
this._send({ op: 'ping' });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
close() {
|
|
74
|
+
if (this.socket) {
|
|
75
|
+
this.connected = false;
|
|
76
|
+
this.socket.end();
|
|
77
|
+
this.socket.destroy();
|
|
78
|
+
this.socket = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
isConnected() {
|
|
83
|
+
return this.connected;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
_send(obj) {
|
|
87
|
+
if (!this.connected || !this.socket) {
|
|
88
|
+
throw new Error('Not connected to broker');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const message = JSON.stringify(obj) + '\n';
|
|
92
|
+
this.socket.write(message);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
_handleData(chunk) {
|
|
96
|
+
this.buffer += chunk.toString();
|
|
97
|
+
|
|
98
|
+
while (this.buffer.includes('\n')) {
|
|
99
|
+
const newlineIndex = this.buffer.indexOf('\n');
|
|
100
|
+
const line = this.buffer.substring(0, newlineIndex).trim();
|
|
101
|
+
this.buffer = this.buffer.substring(newlineIndex + 1);
|
|
102
|
+
|
|
103
|
+
if (line) {
|
|
104
|
+
this._handleLine(line);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
_handleLine(line) {
|
|
110
|
+
try {
|
|
111
|
+
const data = JSON.parse(line);
|
|
112
|
+
|
|
113
|
+
if (data.topic !== undefined && data.data !== undefined) {
|
|
114
|
+
this.emit('message', data.topic, data.data, line);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (data.ok === false && data.error) {
|
|
119
|
+
this.emit('error', data.error, line);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (data.ok === true) {
|
|
124
|
+
this.emit('ok', line);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
this.emit('unknown', data, line);
|
|
129
|
+
} catch (err) {
|
|
130
|
+
this.emit('parseError', err, line);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
module.exports = JoltClient;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
const JoltClient = require('../src/JoltClient');
|
|
2
|
+
|
|
3
|
+
describe('JoltClient', () => {
|
|
4
|
+
let client;
|
|
5
|
+
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
client = new JoltClient({ host: '127.0.0.1', port: 8080 });
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
afterEach(() => {
|
|
11
|
+
if (client.isConnected()) {
|
|
12
|
+
client.close();
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('Configuration', () => {
|
|
17
|
+
test('should use default host and port', () => {
|
|
18
|
+
const defaultClient = new JoltClient();
|
|
19
|
+
expect(defaultClient.host).toBe('127.0.0.1');
|
|
20
|
+
expect(defaultClient.port).toBe(8080);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('should use custom host and port', () => {
|
|
24
|
+
const customClient = new JoltClient({ host: '192.168.1.100', port: 9000 });
|
|
25
|
+
expect(customClient.host).toBe('192.168.1.100');
|
|
26
|
+
expect(customClient.port).toBe(9000);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('Connection', () => {
|
|
31
|
+
test('should connect to broker', async () => {
|
|
32
|
+
await client.connect();
|
|
33
|
+
expect(client.isConnected()).toBe(true);
|
|
34
|
+
}, 10000);
|
|
35
|
+
|
|
36
|
+
test('should emit connected event', async () => {
|
|
37
|
+
const connectedPromise = new Promise(resolve => {
|
|
38
|
+
client.on('connected', resolve);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
await client.connect();
|
|
42
|
+
await connectedPromise;
|
|
43
|
+
}, 10000);
|
|
44
|
+
|
|
45
|
+
test('should handle disconnection', async () => {
|
|
46
|
+
await client.connect();
|
|
47
|
+
|
|
48
|
+
const disconnectedPromise = new Promise(resolve => {
|
|
49
|
+
client.on('disconnected', resolve);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
client.close();
|
|
53
|
+
await disconnectedPromise;
|
|
54
|
+
|
|
55
|
+
expect(client.isConnected()).toBe(false);
|
|
56
|
+
}, 10000);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('Messaging', () => {
|
|
60
|
+
beforeEach(async () => {
|
|
61
|
+
await client.connect();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('should send ping', (done) => {
|
|
65
|
+
client.on('ok', () => {
|
|
66
|
+
done();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
client.ping();
|
|
70
|
+
}, 10000);
|
|
71
|
+
|
|
72
|
+
test('should subscribe to topic', (done) => {
|
|
73
|
+
client.on('ok', () => {
|
|
74
|
+
done();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
client.subscribe('test.topic');
|
|
78
|
+
}, 10000);
|
|
79
|
+
|
|
80
|
+
test('should publish and receive message', (done) => {
|
|
81
|
+
const testTopic = 'test.pubsub';
|
|
82
|
+
const testMessage = 'test message';
|
|
83
|
+
|
|
84
|
+
client.on('message', (topic, data) => {
|
|
85
|
+
if (topic === testTopic && data === testMessage) {
|
|
86
|
+
done();
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
client.subscribe(testTopic);
|
|
91
|
+
|
|
92
|
+
setTimeout(() => {
|
|
93
|
+
client.publish(testTopic, testMessage);
|
|
94
|
+
}, 500);
|
|
95
|
+
}, 10000);
|
|
96
|
+
|
|
97
|
+
test('should handle multiple topics', (done) => {
|
|
98
|
+
const topics = ['topic1', 'topic2', 'topic3'];
|
|
99
|
+
const received = new Set();
|
|
100
|
+
|
|
101
|
+
client.on('message', (topic, data) => {
|
|
102
|
+
received.add(topic);
|
|
103
|
+
|
|
104
|
+
if (received.size === topics.length) {
|
|
105
|
+
done();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
topics.forEach(topic => client.subscribe(topic));
|
|
110
|
+
|
|
111
|
+
setTimeout(() => {
|
|
112
|
+
topics.forEach(topic => {
|
|
113
|
+
client.publish(topic, `message for ${topic}`);
|
|
114
|
+
});
|
|
115
|
+
}, 500);
|
|
116
|
+
}, 10000);
|
|
117
|
+
|
|
118
|
+
test('should handle errors', (done) => {
|
|
119
|
+
client.on('error', (error) => {
|
|
120
|
+
expect(error).toBeDefined();
|
|
121
|
+
done();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
// Try to trigger an error (this depends on broker implementation)
|
|
125
|
+
client.subscribe('');
|
|
126
|
+
}, 10000);
|
|
127
|
+
});
|
|
128
|
+
});
|