-
Notifications
You must be signed in to change notification settings - Fork 1
/
disposable.js
66 lines (61 loc) · 1.58 KB
/
disposable.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var flora = require('@yoda/flora')
var defaultUrl = 'unix:/var/run/flora.sock'
module.exports.once = once
/**
*
* @param {string} name
* @param {object} [options]
* @param {string} [options.url='unix:/var/run/flora.sock']
* @param {number} [options.timeout=15000]
*/
function once (name, options) {
if (options == null) {
options = {}
}
var url = options.url || defaultUrl
var timeout = options.timeout || 15000
var agent = new flora.Agent(url)
return new Promise((resolve, reject) => {
var timer = setTimeout(() => {
agent.close()
reject(new Error(`flora.once timeount for ${timeout}`))
}, timeout)
agent.subscribe(name, msg => {
clearTimeout(timer)
agent.close()
resolve(msg)
})
agent.start()
})
}
module.exports.post = post
/**
*
* @param {string} name
* @param {any[]} msg
* @param {number} [type]
* @param {object} [options]
* @param {string} [options.url='unix:/var/run/flora.sock']
* @returns {number} status code, 0 if post succeeded.
*/
function post (name, msg, type, options) {
if (typeof name !== 'string') {
throw new TypeError('Expect a string on first argument of flora.disposable.post')
}
if (!Array.isArray(msg)) {
throw new TypeError('Expect an array on second argument of flora.disposable.post')
}
if (typeof type !== 'number') {
options = type
type = flora.MSGTYPE_INSTANT
}
if (options == null) {
options = {}
}
var url = options.url || defaultUrl
var agent = new flora.Agent(url)
agent.start()
var ret = agent.post(name, msg, type)
agent.close()
return ret
}