UNPKG

2.36 kBJavaScriptView Raw
1var compose = require('./compose')
2var isArray = Array.isArray
3var multicb = require('multicb')
4
5function split(str) {
6 return isArray(str) ? str : str.split(';')
7}
8
9module.exports = function (plugs, wrap) {
10
11 plugs = plugs.map(function (e) {
12 return isArray(e) ? compose(e, wrap) : e
13 })
14
15 var _self = {
16 name: plugs.map(function (e) { return e.name }).join(';'),
17 client: function (addr, cb) {
18 var _addr = split(addr).find(function (addr) {
19 //connect with the first plug that understands this string.
20 plug = plugs.find(function (plug) {
21 return plug.parse(addr) ? plug : null
22 })
23 if(plug) return addr
24 })
25 if(plug) plug.client(_addr, cb)
26 else cb(new Error('could not connect to:'+addr+', only know:'+_self.name))
27 },
28 server: function (onConnect, onError, startedCb) {
29 //start all servers
30
31 if (!startedCb) {
32 // If a callback is not registered to be called back when the servers are
33 // fully started, our default behaviour is just to print any errors starting
34 // the servers to the log
35 startedCb = (err, result) => {
36 if (err) {
37 console.error("Error starting multiserver server: " + err)
38 }
39 }
40 }
41
42 var started = multicb()
43
44 var closes = plugs.map(function (plug) {
45 return plug.server(onConnect, onError, started())
46 }).filter(Boolean)
47
48 started(startedCb);
49
50 return function (cb) {
51 var done
52 if (cb) done = multicb()
53 closes.forEach(function (close) {
54 if (done && close.length) close(done())
55 else close()
56 })
57 if (done) done(cb)
58 }
59 },
60 stringify: function (scope) {
61 if (!scope) scope = 'device'
62 return plugs
63 .filter(function (plug) {
64 var _scope = plug.scope()
65 return Array.isArray(_scope) ? ~_scope.indexOf(scope) : _scope === scope
66 })
67 .map(function (plug) { return plug.stringify(scope) })
68 .filter(Boolean)
69 .join(';')
70 },
71 //parse doesn't really make sense here...
72 //like, what if you only have a partial match?
73 //maybe just parse the ones you understand?
74 parse: function (str) {
75 return str.split(';').map(function (e, i) {
76 return plugs[i].parse(e)
77 })
78 }
79 }
80 return _self
81}
82
83