UNPKG

2.48 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.BusIndexed = void 0;
4const Bus_1 = require("./Bus");
5/**
6 * A bus that indexes identified actors,
7 * so that actions with a corresponding identifier can be published more efficiently.
8 *
9 * Multiple actors with the same identifier can be subscribed.
10 *
11 * If actors or actions do not have a valid identifier,
12 * then this will fallback to the normal bus behaviour.
13 *
14 * @see Bus
15 *
16 * @template A The actor type that can subscribe to the sub.
17 * @template I The input type of an actor.
18 * @template T The test type of an actor.
19 * @template O The output type of an actor.
20 */
21class BusIndexed extends Bus_1.Bus {
22 /**
23 * All enumerable properties from the `args` object are inherited to this bus.
24 *
25 * @param {IBusIndexedArgs} args Arguments object
26 * @param {string} args.name The name for the bus
27 * @throws When required arguments are missing.
28 */
29 constructor(args) {
30 super(args);
31 this.actorsIndex = {};
32 }
33 subscribe(actor) {
34 const actorId = this.getActorIdentifier(actor) || '_undefined_';
35 let actors = this.actorsIndex[actorId];
36 if (!actors) {
37 actors = this.actorsIndex[actorId] = [];
38 }
39 actors.push(actor);
40 super.subscribe(actor);
41 }
42 unsubscribe(actor) {
43 const actorId = this.getActorIdentifier(actor) || '_undefined_';
44 const actors = this.actorsIndex[actorId];
45 if (actors) {
46 const i = actors.indexOf(actor);
47 if (i >= 0) {
48 actors.splice(i, 1);
49 }
50 if (actors.length === 0) {
51 delete this.actorsIndex[actorId];
52 }
53 }
54 return super.unsubscribe(actor);
55 }
56 publish(action) {
57 const actionId = this.getActionIdentifier(action);
58 if (actionId) {
59 const actors = [...this.actorsIndex[actionId] || [], ...this.actorsIndex._undefined_ || []];
60 return actors.map((actor) => ({ actor, reply: actor.test(action) }));
61 }
62 return super.publish(action);
63 }
64 getActorIdentifier(actor) {
65 return this.actorIdentifierFields.reduce((object, field) => object[field], actor);
66 }
67 getActionIdentifier(action) {
68 return this.actionIdentifierFields.reduce((object, field) => object[field], action);
69 }
70}
71exports.BusIndexed = BusIndexed;
72//# sourceMappingURL=BusIndexed.js.map
\No newline at end of file