forked from ssbc/multiserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
85 lines (74 loc) · 2.37 KB
/
index.js
File metadata and controls
85 lines (74 loc) · 2.37 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
var compose = require('./lib/compose')
var isArray = Array.isArray
var multicb = require('multicb')
function split(str) {
return isArray(str) ? str : str.split(';')
}
module.exports = function (plugs, wrap) {
plugs = plugs.map(function (e) {
return isArray(e) ? compose(e, wrap) : e
})
var _self = {
name: plugs.map(function (e) { return e.name }).join(';'),
client: function (addr, cb) {
let plug
const _addr = split(addr).find(function (addr) {
//connect with the first plug that understands this string.
plug = plugs.find(function (plug) {
return plug.parse(addr) ? plug : null
})
if(plug) return addr
})
if(plug) plug.client(_addr, cb)
else cb(new Error('could not connect to:'+addr+', only know:'+_self.name))
},
server: function (onConnect, onError, startedCb) {
//start all servers
if (!startedCb) {
// If a callback is not registered to be called back when the servers are
// fully started, our default behaviour is just to print any errors starting
// the servers to the log
startedCb = (err, result) => {
if (err) {
console.error("Error starting multiserver server: " + err)
}
}
}
var started = multicb()
var closes = plugs.map(function (plug) {
return plug.server(onConnect, onError, started())
}).filter(Boolean)
started(startedCb);
return function (cb) {
var done
if (cb) done = multicb()
closes.forEach(function (close) {
if (done && close.length) close(done())
else close()
})
if (done) done(cb)
}
},
stringify: function (scope) {
if (!scope) scope = 'device'
return plugs
.filter(function (plug) {
var plugScope = plug.scope()
const isArray = Array.isArray(plugScope)
return isArray ? plugScope.includes(scope) : plugScope === scope
})
.map(function (plug) { return plug.stringify(scope) })
.filter(Boolean)
.join(';')
},
//parse doesn't really make sense here...
//like, what if you only have a partial match?
//maybe just parse the ones you understand?
parse: function (str) {
return str.split(';').map(function (e, i) {
return plugs[i].parse(e)
})
}
}
return _self
}