1 | var compose = require('./compose')
|
2 | var isArray = Array.isArray
|
3 | var multicb = require('multicb')
|
4 |
|
5 | function split(str) {
|
6 | return isArray(str) ? str : str.split(';')
|
7 | }
|
8 |
|
9 | module.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 |
|
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 |
|
30 |
|
31 | if (!startedCb) {
|
32 |
|
33 |
|
34 |
|
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 |
|
72 |
|
73 |
|
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 |
|