/
boomerang.js
90 lines (72 loc) · 2.27 KB
/
boomerang.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
var webservice = require("./webservice");
var utils = require("./utils");
function createTransport(client, options, callback) {
var transport;
var id, replySubject;
var txid = 0;
var pending = {
};
if(typeof options === "function") {
callback = options;
}
function _init() {
id = client.getClientId();
replySubject = "/inbox/" + id;
console.log("init done, replySubject: " + replySubject);
client.subscribe(replySubject, function(inmsg) {
var cb = pending[inmsg.txid];
if(cb) {
delete pending[inmsg.txid];
cb(inmsg.msg);
}
});
if(callback) {
callback(transport);
}
}
transport = {
sendRequest: function(subject, msg, callback) {
var outmsg = {
replySubject: replySubject,
txid: txid,
msg: msg
};
pending[txid] = callback;
client.publish(subject, outmsg);
txid++;
},
listen: function(subject, callback) {
client.subscribe(subject, function(inmsg) {
callback(inmsg.msg, inmsg);
});
},
sendReply: function(msg, inmsg) {
client.publish(inmsg.replySubject, {
txid: inmsg.txid,
msg: msg
});
},
getInboxSubject: function() {
return replySubject;
},
getClient: function() {
return client;
}
};
if(client.getState() !== client.CONNECTED) {
client.connect(_init);
} else {
_init();
}
return transport;
}
// export boomerang as the transport factory
module.exports = createTransport;
// provide the factory as a member
module.exports.transport = createTransport;
// provide a constructor function
module.exports.Transport = function() {
return utils.merge(this, createTransport.apply(this, arguments));
};
// expose the webservice factory
module.exports.webservice = webservice;