-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.js
51 lines (42 loc) · 1.62 KB
/
client.js
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
var events = require('events')
var ipcRenderer = require('electron').ipcRenderer
function Client () {
this.requests = {}
this.remoteEventEmitter = ipcRenderer
this.localEventEmitter = new events.EventEmitter()
this._responseMessageHandler = responseMessageHandler.bind(this)
this.remoteEventEmitter.on('response-message', this._responseMessageHandler)
}
Client.prototype.request = function (action, body, callback) {
if (typeof body === 'function') {
callback = body
body = undefined
}
var id = Math.random().toString(16).slice(2)
var request = {id: id, action: action, body: body}
this.remoteEventEmitter.send('request-message', request)
// We can only handle requests with a callback
if (callback) {
this.requests[request.id] = request
this.requests[request.id].callback = callback
}
}
Client.prototype.on = function (action, callback) {
this.localEventEmitter.on('response-message:' + action, callback)
}
Client.prototype.removeListener = function (action, callback) {
this.localEventEmitter.removeListener('response-message:' + action, callback)
}
Client.prototype.destroy = function () {
this.localEventEmitter.removeAllListeners()
this.remoteEventEmitter.removeListener('response-message', this._responseMessageHandler)
}
function responseMessageHandler (evt, response) {
this.localEventEmitter.emit('response-message:' + response.action, response.error, response.body)
if (response.id) {
var request = this.requests[response.id]
if (request && request.callback) request.callback(response.error, response.body)
this.requests[response.id] = undefined
}
}
module.exports = Client