-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclient.js
More file actions
89 lines (71 loc) · 1.7 KB
/
client.js
File metadata and controls
89 lines (71 loc) · 1.7 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
84
85
86
87
88
89
'use strict'
const { PeerRPCClient } = require('grenache-nodejs-http')
const Link = require('grenache-nodejs-link')
class Client {
constructor (worker, opts = {}) {
this.peer = null
this.link = null
this.worker = worker
this.workerName = this.getWorkerName(worker)
const oDefault = {
grape: 'http://127.0.0.1:30001'
}
this.conf = { ...oDefault, ...opts }
}
getWorkerName (worker) {
if (typeof worker === 'string') {
return worker
}
return worker.name
}
connectGrape (cb = () => {}) {
return new Promise((resolve, reject) => {
if (this.link && this.peer) {
cb(null)
resolve()
return
}
this.link = new Link({
grape: this.conf.grape
})
this.link.start()
this.peer = new PeerRPCClient(this.link, this.conf)
this.peer.init()
resolve()
cb(null)
})
}
request (query, opts, cb) {
return new Promise((resolve, reject) => {
if (typeof opts === 'function') {
this.request(query, { timeout: 10000 }, opts)
return
}
this.connectGrape(() => {
this.peer.request(this.workerName, query, opts, (err, res) => {
if (err) {
if (cb) return cb(err)
reject(err)
return
}
if (cb) return cb(null, res)
resolve(res)
})
})
})
}
stop (cb) {
return new Promise((resolve, reject) => {
if (this.peer && this.link) {
this.peer.stop()
this.link.stop()
}
if (cb) return cb(null)
resolve()
})
}
}
function createClient (worker, opts) {
return new Client(worker, opts)
}
module.exports = createClient