-
Notifications
You must be signed in to change notification settings - Fork 20
/
msgs.js
887 lines (805 loc) · 26 KB
/
msgs.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
* Copyright 2012-2013 the original author or authors
* @license MIT, see LICENSE.txt for details
*
* @author Scott Andrews
*/
(function (define) {
'use strict';
var undef;
/**
* Global msgs bus including all core components and facilities. Domain
* specific functionality is located in other modules that augment this
* object.
*
* Creating child buses for specific tasks or modules of an application is
* highly recommended. Each child bus is able to resolve channels and
* handlers from its parent. Children may export components to a parent
* bus to expose endpoints for a sub-flow.
*
* Advanced functionality may be added to all buses within the system by
* adding properties to this objects 'prototype'.
*/
define(function (require) {
var broadcastDispatcher, directDispatcher, unicastDispatcher, busCounter, channelTopicParserRE;
broadcastDispatcher = require('./channels/dispatchers/broadcast');
directDispatcher = require('./channels/dispatchers/direct');
unicastDispatcher = require('./channels/dispatchers/unicast');
busCounter = counter();
channelTopicParserRE = /^([^!]*)(?:!([\w\W]*))?$/;
/**
* Create a new message
*
* @param {Object} payload content of the message
* @param {Object} [headers] meta data for the message
*/
function Message(payload, headers) {
this.payload = payload;
this.headers = Object.freeze(headers || {});
Object.freeze(this);
}
Message.prototype = {
/**
* Create a new message from this message overriding certain
* headers with the provided values. The current message is not
* modified.
*
* @param {Object} [payload] payload for the new message, defaults
* to the current message payload
* @param {Object} declaredHeaders headers that overwrite the
* current message's headers
* @return {Message} a new message with the same payload and new
* headers
*/
mixin: function (payload, declaredHeaders) {
var headers;
if (arguments.length < 2) {
declaredHeaders = payload;
payload = this.payload;
}
headers = mixin(this.headers);
if (declaredHeaders) {
headers = mixin(headers, declaredHeaders);
}
return new Message(payload, headers);
}
};
/**
* Holds a reference to a channel or handler that can be resolved
* later. Useful for sharing components outside of their home bus.
*/
function Ref(resolver) {
this.resolve = resolver;
}
/**
* @returns true if a Ref
*/
function isRef(ref) {
return ref instanceof Ref;
}
/**
* Create a new message bus
*
* @param {MessageBus} [parent] a parent message bus to extend from
*/
function MessageBus(parent) {
var components = {},
children = [],
busId = busCounter(),
messageCounter = counter();
/**
* @param {Function} [config] configuration helper invoked in the
* context of the bus.
*
* @returns a new message bus who's parent is the current bus
*/
this.bus = function bus(config) {
var messageBus = new MessageBus(this);
children.push(messageBus);
if (config) {
config.call(messageBus, messageBus);
}
return messageBus;
};
/**
* Create a new message
*
* @param {Object|Message} payload the message payload
* @param {Object} [declaredHeaders] the message headers
* @returns the new message
*/
this._message = function _message(payload, declaredHeaders) {
var headers;
headers = {};
declaredHeaders = declaredHeaders || {};
Object.keys(declaredHeaders).forEach(function (header) {
headers[header] = declaredHeaders[header];
}, this);
if (!('id' in declaredHeaders)) {
headers.id = busId + '-' + messageCounter();
}
return this.isMessage(payload) ?
payload.mixin(headers) :
new Message(payload, headers);
};
/**
* Find a handler by name. If the handler is not found in the local
* message bus, the parent message bus is queried.
*
* @param {string|Handler} name the handler name to find
* @returns the found handler, undefined when not found
*/
this.resolveHandler = function resolveHandler(name) {
var handler;
if (this.isHandler(name)) {
return name;
}
if (name in components) {
handler = components[name];
if (isRef(handler)) {
handler = handler.resolve();
}
return this.resolveHandler(handler);
}
if (parent) {
return parent.resolveHandler(name);
}
};
/**
* Find a channel by name. If the channel is not found in the local
* message bus, the parent message bus is queried.
*
* @param {string|Channel} name the channel name to find
* @returns the found channel, undefined when not found
*/
this.resolveChannel = function resolveChannel(name) {
var topic, channel;
if (this.isChannel(name)) {
return name;
}
if (name.match) {
(function (results) {
name = results[1];
topic = results[2];
}(name.match(channelTopicParserRE)));
}
if (name in components) {
channel = components[name];
if (isRef(channel)) {
channel = channel.resolve();
}
channel = this.resolveChannel(channel);
}
else if (parent) {
channel = parent.resolveChannel(name);
}
if (topic) {
channel = topicizeChannel(topic, channel);
}
return channel;
};
/**
* Create an alias for a handler or channel
*
* @param {string} name the alias
* @param {string|Channel|Handler} component the item to register
*/
this.alias = function alias(name, component) {
if (!(this.resolveChannel(component) || this.resolveHandler(component) || isRef(component))) {
throw new Error('Unable to alias: handler or channel is required');
}
if (!name) {
throw new Error('Unable to alias: name is required');
}
if (name in components) {
throw new Error('Unable to alias: the name \'' + name + '\' is in use');
}
components[name] = component;
};
/**
* Dead letter channel that handles messages that were sent, but
* have no handlers.
*/
this.deadLetterChannel = this._channel('deadLetterChannel', broadcastDispatcher());
/**
* Invalid message channel that handles messages when an error was
* encountered sending the message.
*/
this.invalidMessageChannel = this._channel('invalidMessageChannel', broadcastDispatcher());
if (parent) {
// share messages with parent's channels
this.deadLetterChannel.subscribe(this.forward(parent.deadLetterChannel));
this.invalidMessageChannel.subscribe(this.forward(parent.invalidMessageChannel));
/**
* Make a channel available to the parent bus. Useful for
* defining contained sub flows that provide entry and exit
* points.
*
* @param {string} [name] the name to export as
* @param {string|Channel} channel the channel to export
*/
this.exportChannel = function exportChannel(name, channel) {
if (arguments.length === 1) {
channel = name;
}
parent.alias(name, new Ref(function () {
return this.resolveChannel(channel);
}.bind(this)));
};
/**
* Deconstructor that cleans up any lingering state that would
* not be automatically garbage collected
*/
this.destroy = function destroy() {
children.forEach(function (bus) {
bus.destroy();
});
Object.keys(components).forEach(function (name) {
var component = components[name];
if (component.destroy) {
component.destroy();
}
delete components[name];
}, this);
this.deadLetterChannel.destroy();
this.invalidMessageChannel.destroy();
};
}
}
MessageBus.prototype = {
/**
* @returns true if the object is a message
*/
isMessage: function isMessage(message) {
return message instanceof Message;
},
/**
* @returns true if the object can handle messages
*/
isHandler: function isHandler(handler) {
return handler && typeof handler.handle === 'function';
},
/**
* @returns true if the object can send messages
*/
isChannel: function isChannel(channel) {
return channel && typeof channel.send === 'function';
},
/**
* @returns true is the object is a message bus
*/
isBus: function isBus(bus) {
return bus instanceof MessageBus;
},
/**
* Create a new channel to pass messages
*
* @param {string} [name] the name to register this channel under
* @param {Dispatcher} dispatcher dispatching strategy for this
* channel
* @param {string} [type] type of channel, mostly used for tests
* @returns {Channel} a new channel
*/
_channel: function _channel(name, dispatcher, type) {
var taps, channel;
channel = {
send: function send(message) {
if (taps) {
try {
taps.dispatch(message, this.resolveHandler.bind(this));
}
catch (e) {
// squelch, wiretaps must never interfere with normal operation
}
}
try {
if (!dispatcher.dispatch(message, this.resolveHandler.bind(this))) {
if (channel !== this.deadLetterChannel) {
this.send(this.deadLetterChannel, message);
}
}
}
catch (e) {
if (channel !== this.invalidMessageChannel) {
this.send(this.invalidMessageChannel, message, { error: e });
}
}
}.bind(this),
tap: function tap(handler) {
if (!taps) {
taps = broadcastDispatcher();
}
taps.subscribe(handler);
},
untap: function untap(handler) {
if (!taps) {
return;
}
taps.unsubscribe(handler);
},
type: type
};
Object.keys(dispatcher.channelMixins || {}).forEach(function (prop) {
channel[prop] = dispatcher.channelMixins[prop];
});
channel.destroy = function destroy() {
if (taps) {
taps.destroy();
}
if (dispatcher.destroy) {
dispatcher.destroy();
}
};
if (name) {
this.alias(name, channel);
}
return channel;
},
/**
* Create a new handler
*
* @param {string} [name] the name to register this handler under
* @param {Function} transform function to transform the message
* @param {string|Channel} [outputChannel] where to forward the
* handled message
* @param {string|Channel} [inputChannel] channel to receive
* messages from
* @param {string|Channel} [errorChannel] where to forward the
* message when an error occurs
* @returns a new handler
*/
_handler: function _handler(name, transform, outputChannel, inputChannel, errorChannel) {
var handler = {
handle: function handle(message, outputChannelOverride) {
var payload, nextOutput, nextError;
try {
nextOutput = outputChannelOverride || outputChannel || message.headers.replyChannel;
nextError = errorChannel || message.headers.errorChannel;
payload = transform.call(this, message, nextOutput, nextError);
if (payload && nextOutput) {
this.send(nextOutput, payload, message.headers);
}
}
catch (e) {
if (nextError) {
this.send(nextError, message, { error: e });
}
else {
throw e;
}
}
}.bind(this)
};
if (name) {
this.alias(name, handler);
}
if (inputChannel && this.subscribe) {
this.subscribe(inputChannel, handler);
}
return handler;
},
/**
* Create a unicast channel. Messages are load balanced between
* each subscriber. Only one handler receives a copy of each
* message sent to this channel.
*
* @param {string} [name] the name to register this channel under
* @param {Function} [loadBalancer] load balancer
* @returns the channel
*/
channel: optionalName(function channel(name, loadBalancer) {
return this._channel(name, unicastDispatcher(loadBalancer), 'default');
}),
/**
* Subscribe a handler to a channel. The channel must be
* subscribable
*
* @param {string|Channel} from the publishing channel
* @param {string|Handler} to the consuming handler
*/
subscribe: function subscribe(from, to) {
this.resolveChannel(from).subscribe(to);
},
/**
* Unsubscribe a handler from a channel. The channel must be
* subscribable
*
* @param {string|Channel} from the publishing channel
* @param {string|Handler} to the consuming handler
*/
unsubscribe: function unsubscribe(from, to) {
this.resolveChannel(from).unsubscribe(to);
},
/**
* Wire tap a channel. The channel must be tappable
*
* @param {string|Channel} channel the channel to tap
* @param {string|Handler} handler the receiver of tapped messages
*/
tap: function tap(channel, handler) {
this.resolveChannel(channel).tap(handler);
},
/**
* Remove a wire tap from a channel. The channel must be tappable
*
* @param {string|Channel} channel the channel to untap
* @param {string|Handler} handler the receiver of tapped messages
*/
untap: function untap(channel, handler) {
this.resolveChannel(channel).untap(handler);
},
/**
* Create and send a message to a channel
*
* @param {string|Channel} channel the channel to sent the message to
* @param {Object|Message} payload the message to send
* @param {Object} [headers] headers for the message
*/
send: function send(channel, payload, headers) {
this.resolveChannel(channel).send(this._message(payload, headers));
},
/**
* Forwards messages from one channel directly to another
*
* @param {string|Channel} [from] source channel
* @param {string|Channel} to recipient channel
*/
forward: function forward(from, to) {
if (arguments.length === 1) {
to = from;
from = undef;
}
return this._handler(undef, this.utils.noop, to, from);
},
/**
* Subscribe a listener to a channel
*
* @param {string|Channel} channel subscription target
* @param {Function} listener receiver of messages from the target channel.
* The message payload and headeres are provided as arguments to the
* listener.
* @returns {Handler} the subscription handler, needed to unsubscribe
*/
on: function on(channel, listener) {
return this._handler(undef, function (message) {
listener(message.payload, message.headers);
}, this.noopChannel, channel);
},
/**
* Treat an array of handlers as if they are a single handler. Each
* handler is executed in order with the message from the previous
* handler in the pipeline.
*
* @param {string} [name] the name to register the pipeline as
* @param {Array[Handler]} handlers array of handlers
* @param {string|Channel} [opts.output] the channel to forward
* messages to
* @param {string|Channel} [opts.input] the channel to receive
* message from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the pipeline
*/
chain: optionalName(function chain(name, handlers, opts) {
opts = opts || {};
return this._handler(name, function (message) {
handlers.map(this.resolveHandler, this).forEach(function (handler) {
if (!message) { return; }
var m = message;
// unset 'message' forcing it to be handled in order to continue in the chain
message = undef;
handler.handle(m, {
send: function send(m) {
message = m;
return true;
}
});
}, this);
return message;
}, opts.output, opts.input, opts.error);
}),
/**
* Transform messages sent to this channel
*
* @param {string} [name] the name to register the transform as
* @param {Function} transform transform function, invoked with
* message payload and message headers as args, a new payload
* must be returned.
* @param {string|Channel} [opts.output] the channel to forward
* transformed messages to
* @param {string|Channel} [opts.input] the channel to receive
* message from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the transformer
*/
transformer: optionalName(function transformer(name, transform, opts) {
opts = opts || {};
return this._handler(name, function (message) {
return message.mixin(transform.call(undef, message.payload, message.headers), {});
}, opts.output, opts.input, opts.error);
}),
/**
* Filter messages based on some criteria. Abandoned messages may
* be forward to a discard channel if defined.
*
* @param {string} [name] the name to register the filter as
* @param {Function} rule filter function, invoked with message
* payload and message headers as args. If true is returned, the
* message is forwarded, otherwise it is discarded.
* @param {string|Channel} [opts.output] the channel to forward
* messages to
* @param {string|Channel} [opts.discard] channel to handle
* discarded messages
* @param {string|Channel} [opts.input] the channel to receive
* message from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the filter
*/
filter: optionalName(function filter(name, rule, opts) {
opts = opts || {};
return this._handler(name, function (message) {
if (rule.call(this, message.payload, message.headers)) {
return message;
}
else if (opts.discard) {
this.send(opts.discard, message, { discardedBy: name });
}
}, opts.output, opts.input, opts.error);
}),
/**
* Route messages to handlers defined by the rule. The rule may
* return 0..n recipient channels.
* @param {string} [name] the name to register the router as
* @param {Function} rule function that accepts the message and
* defined routes returning channels to route the message to
* @param {Object|Array} [opts.routes] channel aliases for the
* router
* @param {string|Channel} [opts.input] the channel to receive
* message from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the router
*/
router: optionalName(function router(name, rule, opts) {
opts = opts || {};
return this._handler(name, function (message) {
var recipients = rule.call(this, message, opts.routes);
if (!(recipients instanceof Array)) {
recipients = [recipients];
}
opts.routes = opts.routes || {};
recipients.forEach(function (recipient) {
this.send(recipient in opts.routes ? opts.routes[recipient] : recipient, message);
}, this);
}, this.noopChannel, opts.input, opts.error);
}),
/**
* Split one message into many
*
* @param {string} [name] the name to register the splitter as
* @param {Function} rule function that accepts a message and
* returns an array of messages
* @param {string|Channel} [opts.output] the channel to forward
* split messages to
* @param {string|Channel} [opts.input] the channel to receive
* message from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the splitter
*/
splitter: optionalName(function splitter(name, rule, opts) {
opts = opts || {};
return this._handler(name, function (message) {
rule.call(this, message).forEach(function (splitMessage, index, splitMessages) {
this.send(opts.output, splitMessage, {
sequenceNumber: index,
sequenceSize: splitMessages.length,
correlationId: message.headers.id
});
}, this);
}, this.noopChannel, opts.input, opts.error);
}),
/**
* Aggregate multiple messages into a single message
*
* @param {string} [name] the name to register the aggregator as
* @param {Function} strategy function that accepts a message and
* a callback function. When the strategy determines a new
* message is ready, it must invoke the callback function with
* that message.
* @param {string|Channel} [opts.output] the channel to forward
* aggregated messages to
* @param {string|Channel} [opts.input] the channel to receive
* message from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the aggregator
*/
aggregator: optionalName(function aggregator(name, correlator, opts) {
opts = opts || {};
var release = function (payload, headers) {
this.send(opts.output, payload, headers);
}.bind(this);
return this._handler(name, function (message) {
correlator.call(this, message, release);
}, this.noopChannel, opts.input, opts.error);
}),
/**
* Log messages at the desired level
*
* @param {string} [name] the name to register the logger as
* @param {Console} [opts.console=console] the console to log with
* @param {string} [opts.level='log'] the console level to log at,
* defaults to 'log'
* @param {Object|string} [opts.prefix] value included with the
* logged message
* @param {string|Channel} [opts.tap] the channel to log messages
* from
* @returns the logger
*/
logger: optionalName(function logger(name, opts) {
opts = opts || {};
opts.console = opts.console || console;
opts.level = opts.level || 'log';
var handler, channel;
handler = this._handler(name, function (message) {
var output = 'prefix' in opts ?
[opts.prefix, message] :
[message];
opts.console[opts.level].apply(opts.console, output);
}, this.noopChannel);
channel = this.resolveChannel(opts.tap);
if (channel && channel.tap) {
channel.tap(handler);
}
return handler;
}),
/**
* Post messages to a channel that can be invoked as a JS function.
* The first argument of the returned function becomes the message
* payload.
*
* @param {string|Channel} output the channel to post messages to
* @param {Function} [adapter] function to adapt the arguments into
* a message payload. The function must return a message payload.
* @returns a common function that sends messages
*/
inboundAdapter: function inboundAdapter(output, adapter) {
var counter = this.utils.counter();
adapter = adapter || this.utils.noop;
return function () {
var payload = adapter.apply(arguments[0], arguments);
if (payload !== undef) {
this.send(output, payload, { sequenceNumber: counter() });
}
}.bind(this);
},
/**
* Bridge a handler to a common function. The function is invoked
* as messages are handled with the message payload provided as an
* argument.
*
* @param {string} [name] the name to register the adapter as
* @param {Function} func common JS function to invoke
* @param {string|Channel} opts.input the channel to output
* messages for
* @param {string|Channel} [opts.error] channel to receive errors
* @returns {Handler} the handler for this adapter
*/
outboundAdapter: optionalName(function outboundAdapter(name, func, opts) {
opts = opts || {};
return this._handler(name, function (message) {
func.call(undef, message.payload);
}, this.noopChannel, opts.input, opts.error);
}),
/**
* Channel that does nothing
*/
noopChannel: Object.freeze({
send: function () {
return true;
}
}),
/**
* Handler that does nothing
*/
noopHandler: Object.freeze({
handle: function () {}
}),
/**
* Common helpers that are useful to other modules but not worthy
* of their own module
*/
utils: {
counter: counter,
mixin: mixin,
noop: function noop() { return arguments[0]; },
optionalName: optionalName,
topicizeChannel: topicizeChannel
}
};
// make it easy for custom extensions to the MessageBus prototype
MessageBus.prototype.prototype = MessageBus.prototype;
return new MessageBus();
});
/**
* Incrementing counter
*/
function counter() {
/*jshint plusplus:false */
var count = 0;
return function increment() {
return count++;
};
}
/**
* Mixin util. Copies properties from the props object to the target object.
* Will create a shallow clone if only one args is provided.
*
* @param {Object} target the object to copy properties to
* @param {Object} [props] the source of properties to copy
*/
function mixin(target, props) {
if (arguments.length < 2) {
props = target;
target = {};
}
for (var prop in props) {
if (props.hasOwnProperty(prop)) {
target[prop] = props[prop];
}
}
return target;
}
/**
* Detect if the first parameter is a name. If the param is omitted,
* arguments are normalized and passed to the wrapped function.
* Behavior is undesirable if the second argument can be a string.
*
* @param {Function} func function who's first parameter is a name that
* may be omitted.
*/
function optionalName(func) {
return function (name) {
var args = Array.prototype.slice.call(arguments);
if (typeof name !== 'string') {
// use empty string instead of undef so that this optionalName helpers can be stacked
args.unshift('');
}
return func.apply(this, args);
};
}
/**
* Transform a channel to enable topical subscriptions. Wraps the channel's
* 'send', 'subscribe' and 'unsubscribe' augmenting the method args with the
* topic info.
*
* The original channel is unaffected.
*
* @param {string} topic the topic
* @param {Channel} the channel to topicize
* @returns {Channel} the channel topicized
*/
function topicizeChannel(topic, channel) {
var send, subscribe, unsubscribe;
send = channel.send;
subscribe = channel.subscribe;
unsubscribe = channel.unsubscribe;
channel = Object.create(channel);
if (send) {
channel.send = function (message) {
return send.call(this, message.mixin({ topic: topic }));
};
}
if (subscribe) {
channel.subscribe = function (handler) {
return subscribe.call(this, topic, handler);
};
}
if (unsubscribe) {
channel.unsubscribe = function (handler) {
return unsubscribe.call(this, topic, handler);
};
}
return channel;
}
}(
typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }
// Boilerplate for AMD and Node
));