1 | import R from "ramda";
|
2 | import pubsubFactory from "mq-pubsub";
|
3 |
|
4 |
|
5 |
|
6 | /**
|
7 | * Handles the pub/sub events used to communicate between multiple instances
|
8 | * of app-sync running within different containers.
|
9 | *
|
10 | * @param {String} uid: The unique identifier of the main app-sync instance.
|
11 | * @param {Array} apps: The array containing the collection of apps.
|
12 | * @param {String} url: The URL to the RabbitMQ server.
|
13 | *
|
14 | * @return {Object} The internal pub/sub API.
|
15 | */
|
16 | export default (uid, apps, url) => {
|
17 | // Setup initial conditions.
|
18 | if (!url) { throw new Error("A URL to the RabbitMQ server is required."); }
|
19 |
|
20 | // Setup the pub/sub event.
|
21 | const pubsub = pubsubFactory(url);
|
22 | const appUpdatedEvent = pubsub.event("app:updated");
|
23 |
|
24 | // Listen for events from the other containers.
|
25 | appUpdatedEvent.subscribe(payload => {
|
26 | if (payload.uid !== uid) {
|
27 | // The app was updated within another container, restart it now.
|
28 | const app = R.find(item => item.id === payload.data.id, apps);
|
29 | if (app) {
|
30 | app.start();
|
31 | }
|
32 | }
|
33 | });
|
34 |
|
35 |
|
36 | // Api.
|
37 | return {
|
38 | /**
|
39 | * Publishes an event that all app-sync instances the
|
40 | * running containers will hear.
|
41 | *
|
42 | * @param {String} event: The name of the event to fire.
|
43 | * @param {object} data: The event details.
|
44 | *
|
45 | */
|
46 | publish(event, data) {
|
47 | switch (event) {
|
48 | case "app:updated":
|
49 | appUpdatedEvent.publish({ uid, data });
|
50 | break;
|
51 | default: throw new Error(`The '${ event }' event is not supported.`);
|
52 | }
|
53 | }
|
54 | };
|
55 |
|
56 | };
|