-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (71 loc) · 2.28 KB
/
index.js
File metadata and controls
83 lines (71 loc) · 2.28 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const EventEmitter = require('events');
const ipc = require('node-ipc');
class ipcClient extends EventEmitter {
constructor({name}) {
super();
if (!name) {
throw new Error('No client name provided in env vars!');
}
console.info(`Creating ipc client with ID ${name}`);
this.name = name;
this.promises = [];
ipc.config.id = name;
ipc.config.silent = true;
this._connect();
}
_connect() {
ipc.connectTo(
'master',
() => {
ipc.of.master.on(this.name, this._onMessage.bind(this));
}
);
}
_onMessage({ topic, payload, requestId }) {
if (requestId) {
this._resolvePromise({ requestId, topic, payload });
} else {
this.emit('message', { topic, payload });
}
}
_resolvePromise({ payload, requestId }) {
const promiseObject = this.promises.find(item => item.requestId === requestId);
if (promiseObject) {
this._removePromise(promiseObject)
clearTimeout(promiseObject.rejectTimer);
promiseObject.resolve(payload);
}
}
_removePromise(ref) {
const index = this.promises.indexOf(ref);
if (index !== -1) {
this.promises.splice(index, 1);
}
}
request({ topic, payload, timeout = 2000 }) {
const requestId = Date.now() + Math.random();
const promiseObject = { requestId };
const rejectTimer = setTimeout(() => {
promiseObject.reject({ success: false, reason: 'timeout' });
this._removePromise(promiseObject);
}, timeout);
const promise = new Promise((resolve, reject) => {
promiseObject.resolve = resolve;
promiseObject.reject = reject;
});
this.promises.push(promiseObject);
this.send({ topic, payload, requestId });
return promise;
}
send({ topic = '', payload, requestId }) {
if (typeof ipc.of.master !== 'undefined') {
ipc.of.master.emit(
this.name,
{topic, payload, requestId}
)
} else {
console.error('Connection not ready yet!');
}
}
}
module.exports = ipcClient;