forked from pryv/lib-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.js
More file actions
44 lines (41 loc) · 1.5 KB
/
Socket.js
File metadata and controls
44 lines (41 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* @license
* [BSD-3-Clause](https://github.com/pryv/lib-js/blob/master/LICENSE)
*/
const UpdateMethod = require('./UpdateMethod');
const Changes = require('../lib/Changes');
/**
* Update method that uses @pryv/socket.io events for real-time updates.
* Requires @pryv/socket.io to be loaded.
* @memberof pryv.Monitor
* @extends UpdateMethod
*/
class Socket extends UpdateMethod {
async ready () {
if (this.socket) return;
// @ts-ignore - socket is added by @pryv/socket.io extension
if (!this.monitor.connection.socket) {
throw new Error('You should load package @pryv/socket.io to use monitor with websockets');
}
// @ts-ignore - socket is added by @pryv/socket.io extension
this.socket = await this.monitor.connection.socket.open();
this.socket.on('eventsChanged', () => { this.monitor.updateEvents(); });
this.socket.on('streamsChanged', () => { this.monitor.updateStreams(); });
this.socket.on('error', (error) => {
this.monitor.emit(Changes.ERROR, error);
// If the underlying socket.io-client transport has been torn down
// (i.e. SocketIO emitted 'error' after reconnect_failed), drop our
// reference so a future Changes.READY can rebuild instead of
// short-circuiting on the cached, dead handle.
if (this.socket && !this.socket._io) {
this.socket = null;
}
});
}
async stop () {
if (!this.socket) return;
try { this.socket.close(); } catch (e) { }
this.socket = null;
}
}
module.exports = Socket;