forked from ruidfigueiredo/electron-cgi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.js
More file actions
47 lines (38 loc) · 1.28 KB
/
connection.js
File metadata and controls
47 lines (38 loc) · 1.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
const Request = require('./request');
const TabSeparatedInputStreamParser = require('./tab-separated-input-stream-parser');
function Connection(outStream, inStream) {
const responseHandlersQueue = [];
const inputStreamParser = new TabSeparatedInputStreamParser();
inStream.setEncoding('utf8');
inStream.on('data', (chunk) => {
inputStreamParser.addPartial(chunk);
});
inStream.on('close', () => {
if (this.onDisconnect) {
this.onDisconnect();
}
});
inputStreamParser.onResponse(response => {
const responseIds = responseHandlersQueue.map(r => r.id);
if (responseIds.indexOf(response.id) !== -1) {
responseHandlersQueue.splice(responseIds.indexOf(response.id), 1)[0].onResponse(response.result);
}
});
const send = (request, onResponse) => {
outStream.write(`${JSON.stringify(request)}\t`);
if (onResponse) {
responseHandlersQueue.push({
id: request.id,
onResponse
});
}
};
this.onDisconnect = null;
this.send = (type, args = {}, onResponse = null) => {
send(new Request(type, args), onResponse);
};
this.close = () => {
outStream.end();
};
}
module.exports = Connection;