forked from SocketCluster/sc-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (49 loc) · 1.57 KB
/
index.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
var redis = require('redis');
module.exports.attach = function (broker) {
var brokerOptions = broker.options.brokerOptions;
var instanceId = broker.instanceId;
var subClient = redis.createClient(brokerOptions.port, brokerOptions.host, brokerOptions);
var pubClient = redis.createClient(brokerOptions.port, brokerOptions.host, brokerOptions);
broker.on('subscribe', subClient.subscribe.bind(subClient));
broker.on('unsubscribe', subClient.unsubscribe.bind(subClient));
broker.on('publish', function (channel, data) {
if (data instanceof Object) {
try {
data = '/o:' + JSON.stringify(data);
} catch (e) {
data = '/s:' + data;
}
} else {
data = '/s:' + data;
}
if (instanceId != null) {
data = instanceId + data;
}
pubClient.publish(channel, data);
});
var instanceIdRegex = /^[a-z0-9-]*\//;
subClient.on('message', function (channel, message) {
var sender = null;
message = message.replace(instanceIdRegex, function (match) {
sender = match.slice(0, -1);
return '';
});
// Do not publish if this message was published by
// the current SC instance since it has already been
// handled internally
if (sender == null || sender != instanceId) {
var type = message.charAt(0);
var data;
if (type == 'o') {
try {
data = JSON.parse(message.slice(2));
} catch (e) {
data = message.slice(2);
}
} else {
data = message.slice(2);
}
broker.publish(channel, data);
}
});
};