diff --git a/index.js b/index.js index 61138df..890331f 100644 --- a/index.js +++ b/index.js @@ -30,7 +30,7 @@ function Adapter(nsp){ * Inherits from `EventEmitter`. */ -Adapter.prototype.__proto__ = Emitter.prototype; +Adapter.prototype = Object.create(Emitter.prototype); /** * Adds a socket from a room. @@ -83,6 +83,44 @@ Adapter.prototype.delAll = function(id, fn){ delete this.sids[id]; }; + +/** + * Get all clients in room. + * + * @param {String} room id + * @api public + */ +Adapter.prototype.clients = function(room, fn){ + // One argument + if(!fn){ + if(typeof(room) !== 'function'){ + return; + } + fn = room; + room = null; + } + + var result; + if(room === null){ + result = Object.keys(this.sids || []); + } + else{ + result = Object.keys(this.rooms[room] || []); + } + process.nextTick(fn.bind(null, null, result)); +}; + +/** + * Get all rooms the client is in. + * + * @param {String} client id + * @api public + */ +Adapter.prototype.roomClients = function(id, fn){ + var result = Object.keys(this.sids[id] || []); + process.nextTick(fn.bind(null, null, result)); +}; + /** * Broadcasts a packet. * diff --git a/test/index.js b/test/index.js new file mode 100644 index 0000000..904a87b --- /dev/null +++ b/test/index.js @@ -0,0 +1,188 @@ +var expect = require('expect.js'); +var async = require('async'); +var Adapter = require('../index.js'); + +describe('socket.io-adapter', function(){ + var adapter; + var fakensp; + before(function(done){ + fakensp = { + name: 'test', + connected: [] + }; + async.times(20, function(n, next){ + fakensp.connected[n.toString()] = {}; + next(); + }, + done); + }); + describe('Adapter', function(){ + it('should construct the adapter', function(){ + adapter = new Adapter(fakensp); + expect(adapter).to.be.an(Adapter); + }); + }); + describe('add', function(){ + it('should add a socket to a room', function(){ + var room = 'a'; + var sid = '1'; + adapter.add(sid, room, function(){ + expect(adapter.sids).to.be.an('object'); + expect(adapter.sids[sid]).to.be.an('object'); + expect(adapter.sids[sid][room]).to.equal(true); + expect(adapter.rooms[room]).to.be.an('object'); + expect(adapter.rooms[room][sid]).to.equal(true); + }); + }); + }); + describe('del', function(){ + it('should remove a socket from aroom', function(){ + var room = 'a'; + var sid = '1'; + adapter.del(sid, room); + expect(adapter.sids[sid]).to.not.contain(room); + expect(adapter.rooms[room]).to.not.contain(room); + }); + }); + describe('delAll', function(){ + var sid = 'a'; + var rooms = []; + + before(function(done){ + //Clear rooms and sockets + adapter.sids = {}; + adapter.rooms = {}; + + //Add the socket to multiple rooms + async.times(10, function(n, next){ + rooms.push(n); + adapter.add(sid, n, function(){ + next(); + }); + }, done); + }); + + it('should remove a socket from all rooms', function(done){ + var rooms = Object.keys(adapter.rooms); + var i; + for(i=0; i