1 | // Copyright © 2017, 2018 IBM Corp. All rights reserved.
|
2 | //
|
3 | // Licensed under the Apache License, Version 2.0 (the "License");
|
4 | // you may not use this file except in compliance with the License.
|
5 | // You may obtain a copy of the License at
|
6 | //
|
7 | // http://www.apache.org/licenses/LICENSE-2.0
|
8 | //
|
9 | // Unless required by applicable law or agreed to in writing, software
|
10 | // distributed under the License is distributed on an "AS IS" BASIS,
|
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 | // See the License for the specific language governing permissions and
|
13 | // limitations under the License.
|
14 | ;
|
15 |
|
16 | const debug = require('debug')('cloudant:eventrelay');
|
17 |
|
18 | /**
|
19 | * Relay all events from a source emitter to a target emitter.
|
20 | *
|
21 | * @param {Object} source - Source event emitter.
|
22 | * @param {Object} target - Target event emitter.
|
23 | */
|
24 | class EventRelay {
|
25 | constructor(source, target) {
|
26 | var self = this;
|
27 |
|
28 | if (typeof target === 'undefined') {
|
29 | self._target = source;
|
30 | } else {
|
31 | self._target = target;
|
32 | self.setSource(source);
|
33 | }
|
34 |
|
35 | self._paused = true;
|
36 | self._eventsStash = [];
|
37 | }
|
38 |
|
39 | // Clear all stashed events.
|
40 | clear() {
|
41 | this._eventsStash = [];
|
42 | }
|
43 |
|
44 | // Pause event relay.
|
45 | pause() {
|
46 | this._paused = true;
|
47 | }
|
48 |
|
49 | // Resume event relay and fire all stashed events.
|
50 | resume() {
|
51 | var self = this;
|
52 |
|
53 | this._paused = false;
|
54 |
|
55 | debug('Relaying captured events to target stream.');
|
56 | self._eventsStash.forEach(function(event) {
|
57 | self._target.emit.apply(self._target, event);
|
58 | });
|
59 | }
|
60 |
|
61 | // Set a new source event emitter.
|
62 | setSource(source) {
|
63 | var self = this;
|
64 |
|
65 | self.clear();
|
66 | self.pause();
|
67 |
|
68 | debug('Setting new source stream.');
|
69 | self._source = source;
|
70 |
|
71 | self._oldEmit = self._source.emit;
|
72 | self._source.emit = function() {
|
73 | if (self._paused) {
|
74 | self._eventsStash.push(arguments);
|
75 | } else {
|
76 | self._target.emit.apply(self._target, arguments);
|
77 | }
|
78 | self._oldEmit.apply(self._source, arguments);
|
79 | };
|
80 | }
|
81 | }
|
82 |
|
83 | module.exports = EventRelay;
|