UNPKG

2.9 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const ChannelManager_1 = require("./ChannelManager");
4const EXCHANGE_PREFIX = "nimbus:event:";
5const EXCHANGE_ALL_EVENTS = "nimbus:events";
6const EXCHANGE_EVENTS_BY_USER = "nimbus:eventsByUser";
7const EXCHANGE_OPTIONS = { durable: true, autoDelete: false };
8class Event {
9 constructor(options) {
10 this.exchange = options.exchange;
11 this.userId = options.userId;
12 this.topic = options.topic ? options.topic : 'nimbusEvent';
13 }
14 send(object) {
15 return this.sendString(this.prepareMessage(object));
16 }
17 get fullExchangeName() {
18 if (this.userId)
19 return EXCHANGE_EVENTS_BY_USER;
20 return EXCHANGE_PREFIX + this.exchange;
21 }
22 get routeKey() {
23 return this.exchange + '.' + this.topic + (this.userId ? '.' + this.userId : '');
24 }
25 assertExchange() {
26 return ChannelManager_1.channelManager.getChannel().then((channel) => {
27 return new Promise((resolve, reject) => {
28 channel.assertExchange(this.fullExchangeName, "topic", EXCHANGE_OPTIONS, (err) => err ? reject(err) : resolve(channel));
29 });
30 });
31 }
32 assertExchangeForAllEvents() {
33 return ChannelManager_1.channelManager.getChannel().then((channel) => {
34 if (this.userId)
35 return channel;
36 return new Promise((resolve, reject) => {
37 channel.assertExchange(EXCHANGE_ALL_EVENTS, "topic", EXCHANGE_OPTIONS, (err) => err ? reject(err) : resolve(channel));
38 });
39 });
40 }
41 bindToExchangeForAllEvents() {
42 return ChannelManager_1.channelManager.getChannel().then((channel) => {
43 if (this.userId)
44 return channel;
45 return new Promise((resolve, reject) => {
46 channel.bindExchange(EXCHANGE_ALL_EVENTS, this.fullExchangeName, "#", {}, (err) => err ? reject(err) : resolve(channel));
47 });
48 });
49 }
50 sendBuffer(buffer) {
51 return ChannelManager_1.channelManager.getChannel()
52 .then(() => this.assertExchange())
53 .then(() => this.assertExchangeForAllEvents())
54 .then(() => this.bindToExchangeForAllEvents())
55 .then((channel) => {
56 channel.publish(this.fullExchangeName, this.routeKey, buffer, {
57 contentType: "text/json",
58 persistent: true
59 });
60 });
61 }
62 sendString(string) {
63 return this.sendBuffer(new Buffer(string));
64 }
65 prepareMessage(object) {
66 var message = {
67 exchange: this.exchange,
68 topic: this.topic,
69 content: object
70 };
71 if (this.userId)
72 message.userId = this.userId;
73 return JSON.stringify(message);
74 }
75}
76exports.Event = Event;
77//# sourceMappingURL=Event.js.map
\No newline at end of file