1 | 'use strict';
|
2 |
|
3 | const { KellnerPassThrough } = require('../streams');
|
4 | const { kellnerApp, kellnerWires } = require('../symbols');
|
5 |
|
6 | class IoPort {
|
7 | constructor(app) {
|
8 | this[kellnerApp] = app;
|
9 | this[kellnerWires] = [];
|
10 | this.incoming = new KellnerPassThrough(this[kellnerApp]);
|
11 | this.outgoing = new KellnerPassThrough(this[kellnerApp]);
|
12 | }
|
13 |
|
14 | getApp() {
|
15 | return this[kellnerApp];
|
16 | }
|
17 |
|
18 | in(wire) {
|
19 | return this._use(wire, { incoming: this.incoming });
|
20 | }
|
21 |
|
22 | out(wire) {
|
23 | return this._use(wire, { outgoing: this.outgoing });
|
24 | }
|
25 |
|
26 | use(wire) {
|
27 | return this._use(wire, { incoming: this.incoming, outgoing: this.outgoing });
|
28 | }
|
29 |
|
30 | _use(wire, {
|
31 | incoming,
|
32 | outgoing,
|
33 | }) {
|
34 | if (!wire)
|
35 | throw new Error('Wire is missing.');
|
36 |
|
37 | if (typeof wire.link !== 'function')
|
38 | throw new Error('Wire must have a link funciton');
|
39 |
|
40 | if (typeof wire.prelink === 'function')
|
41 | wire.prelink(this);
|
42 |
|
43 | this[kellnerWires].push(() => wire.link(this[kellnerApp], { incoming, outgoing }));
|
44 |
|
45 | return this;
|
46 | }
|
47 |
|
48 | async link() {
|
49 | await Promise.all(this[kellnerWires].map(a => a()));
|
50 | }
|
51 | }
|
52 |
|
53 | module.exports = IoPort;
|