-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (62 loc) · 1.72 KB
/
Copy pathindex.js
File metadata and controls
69 lines (62 loc) · 1.72 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import io from 'socket.io-client';
import EventEmitter from 'events';
import { serializeError, deserializeError } from 'serialize-error';
function logEvent (eventName) {
return function (data) {
console.log(`Event ${eventName}`, data);
}
}
function logError (eventName) {
return function (err) {
console.error(`Error ${eventName}`);
console.error(serializeError(err));
}
}
class IbpApi extends EventEmitter {
constructor(options) {
super();
this.url = options.url;
this.apiKey = options.apiKey;
this.socket = io(this.url, {
query: {
workerId: 'api-test',
apiKey: this.apiKey,
capabilities: [], // none, we won't be doing any work
}
});
this.socket
.on('connect', logEvent('connect'))
.on('disconnect', logEvent('connect'))
.on('parse_error', logEvent('parse_error'))
.on('connect_error', logError('connect_error'))
.on('error', logError('error'))
.on('events', function(data) {
console.log('Received events:', data);
})
}
/**
* Eg: subscribe('healthCheck', 'created')
* @param {*} event
*/
subscribe(event, ...args) {
const model = event; // .split('_')[0];
// const eventName = event.split('_')[1];
// TODO: support multiple events, like 'created', 'updated', 'deleted'
const eventName = `subscribe_${model}`;
this.socket.emit(eventName);
this.socket.on(model, (data) => {
this.emit(model, data);
});
}
/**
* Eg: unsubscribe('healthCheck')
* @param {*} event
*/
unsubscribe(event) {
const model = event; // .split('_')[0];
const eventName = `unsubscribe_${model}`
this.socket.emit(eventName);
this.socket.off(model);
}
}
export { IbpApi };