Skip to content

Commit

Permalink
adapter: initial memory impl
Browse files Browse the repository at this point in the history
  • Loading branch information
rauchg committed Dec 24, 2012
1 parent 95d8e75 commit 67f7d57
Showing 1 changed file with 122 additions and 0 deletions.
122 changes: 122 additions & 0 deletions lib/adapter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@

/**
* Module dependencies.
*/

var Emitter = require('events').EventEmitter;

/**
* Module exports.
*/

module.exports = Adapter;

/**
* Memory adapter constructor.
*
* @param {Namespace} nsp
* @api public
*/

function Adapter(nsp){
this.nsp = nsp;
this.rooms = {};
this.sids = {};
}

/**
* Inherits from `EventEmitter`.
*/

Adapter.prototype.__proto__ = Emitter.prototype;

/**
* Adds a socket from a room.
*
* @param {String} socket id
* @param {String} room name
* @param {Function} callback
* @api public
*/

Adapter.prototype.add = function(id, room, fn){
this.sids[id] = this.sids[id] || {};
this.sids[id][room] = true;
this.rooms[room] = this.rooms[room] || [];
this.rooms[room][id] = true;
if (fn) process.nextTick(fn.bind(null, null));
};

/**
* Removes a socket from a room.
*
* @param {String} socket id
* @param {String} room name
* @param {Function} callback
* @api public
*/

Adapter.prototype.del = function(id, room, fn){
this.sids[id] = this.sids[id] || {};
this.rooms[room] = this.rooms[room] || {};
delete this.sids[id][room];
delete this.rooms[room][id];
if (fn) process.nextTick(fn.bind(null, null));
};

/**
* Removes a socket from all rooms it's joined.
*
* @param {String} socket id
* @api public
*/

Adapter.prototype.delAll = function(id, fn){
var rooms = this.sids[id];
if (rooms) {
for (var room in rooms) {
delete this.rooms[room][id];
}
}
delete this.sids[id];
};

/**
* Broadcasts a packet.
*
* Options:
* - `flags` {Object} flags for this packet
* - `except` {Array} sids that should be excluded
* - `rooms` {Array} list of rooms to broadcast to
*
* @param {Object} packet object
* @api public
*/

Adapter.prototype.broadcast = function(packet, opts){
var rooms = opts.rooms || [];
var except = opts.except || [];
var ids = {};
var socket;

if (rooms.length) {
for (var i = 0; i < rooms.length; i++) {
var room = this.rooms[rooms[i]];
if (!room) continue;
for (var id in room) {
if (ids[id] || ~except.indexOf(id)) continue;
socket = this.nsp.connected[id];
if (socket) {
socket.packet(packet);
ids[id] = true;
}
}
}
} else {
for (var id in this.sids) {
if (~except.indexOf(id)) continue;
socket = this.nsp.connected[id];
if (socket) socket.packet(packet);
}
}
};

0 comments on commit 67f7d57

Please sign in to comment.