-
Notifications
You must be signed in to change notification settings - Fork 3
/
publisher.js
64 lines (51 loc) · 1.68 KB
/
publisher.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
var uuid = require('node-uuid');
var AMQP = require('./amqp.js');
var Storage = require('./storage.js');
function Publisher(config) {
if (!this.domain) throw new Error('Missing domain property');
this.amqp = new AMQP(config.amqp);
this.storage = new Storage(config.storage);
}
Publisher.prototype.connect = function (callback) {
var self = this;
this.storage.initAdapters(function (err) {
if (err) return callback(err);
self.amqp.connect().then(function (channel) {
self.channel = channel;
callback(null, channel);
}, callback);
});
};
Publisher.prototype.askRPC = function (event, callback) {
var self = this;
this.persistEvent(event, function (err) {
if (err) return callback(err);
self.emitEvent(event, callback);
});
};
Publisher.prototype.persistEvent = function (event, callback) {
this.storage.persistEvent(event, callback);
};
Publisher.prototype.assertReplyQueue = function () {
return this.channel.assertQueue('', { exclusive: true }).then(function (queueAssertion) {
return queueAssertion.queue;
});
};
Publisher.prototype.emitEvent = function (event, callback) {
event = new Buffer(JSON.stringify(event));
var queue = this.domain;
if (!callback) return this.channel.sendToQueue(queue, event);
var self = this;
var rpcConfig = { correlationId: uuid.v4(), replyTo: null };
var rpcCallback = function (msg) {
if (msg.properties.correlationId !== rpcConfig.correlationId) return;
callback(msg);
};
this.assertReplyQueue().then(function (responseQ) {
self.channel.consume(responseQ, rpcCallback, { noAck: true }).then(function () {
rpcConfig.replyTo = responseQ;
self.channel.sendToQueue(queue, event, rpcConfig);
});
});
};
module.exports = Publisher;