Last active
September 9, 2015 13:41
-
-
Save bjyoungblood/11b346293f5ead88ce7a to your computer and use it in GitHub Desktop.
Example Nes Redis Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load modules | |
var Util = require('util'); | |
var EventEmitter = require('events').EventEmitter; | |
var Redis = require('redis'); | |
// Declare internals | |
var internals = {}; | |
exports = module.exports = internals.Adapter = function () { | |
var self = this; | |
EventEmitter.call(this); | |
this._pub = Redis.createClient.apply(null, arguments); | |
this._sub = Redis.createClient.apply(null, arguments); | |
this._pub.on('error', function(err) { | |
self.emit('error', err); | |
}); | |
this._sub.on('error', function(err) { | |
self.emit('error', err); | |
}); | |
this._sub.psubscribe('nes:*', function(err) { | |
if (err) { | |
self.emit(err); | |
} | |
}); | |
this._sub.on('pmessage', function(pattern, channel, message) { | |
var parsed = JSON.parse(message); | |
if (channel === 'nes:publish') { | |
self.emit('publish', parsed.path, parsed.message); | |
} else if (channel === 'nes:broadcast') { | |
self.emit('broadcast', parsed.message); | |
} | |
}); | |
}; | |
Util.inherits(internals.Adapter, EventEmitter); | |
internals.Adapter.prototype.broadcast = function (update) { | |
this._pub.publish('nes:broadcast', JSON.stringify({ | |
message : update | |
})); | |
}; | |
internals.Adapter.prototype.publish = function (path, message) { | |
this._pub.publish('nes:publish', JSON.stringify({ | |
path : path, | |
message : message | |
})); | |
}; | |
internals.Adapter.prototype.stop = function () { | |
this._pub.end(); | |
this._sub.end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment