diff --git a/src/swarm.js b/src/swarm.js index 3f89f9f0..b35bef3c 100644 --- a/src/swarm.js +++ b/src/swarm.js @@ -20,7 +20,7 @@ function Swarm () { self.port = parseInt(process.env.IPFS_SWARM_PORT, 10) || 4001 self.connections = {} // {peerIdB58: {conn: <>, socket: <>} - self.handles = [] + self.handles = {} // set the listener @@ -140,7 +140,7 @@ function Swarm () { if (self.handles[protocol]) { return handlerFunc(new Error('Handle for protocol already exists', protocol)) } - self.handles.push({ protocol: protocol, func: handlerFunc }) + self.handles[protocol] = handlerFunc log.info('Registered handler for protocol:', protocol) } @@ -165,8 +165,8 @@ function Swarm () { errorUp(self, stream) var msH = new Select() msH.handle(stream) - self.handles.forEach(function (handle) { - msH.addHandler(handle.protocol, handle.func) + Object.keys(self.handles).forEach(function (protocol) { + msH.addHandler(protocol, self.handles[protocol]) }) } diff --git a/tests/swarm-test.js b/tests/swarm-test.js index 7fc7e265..28e87d58 100644 --- a/tests/swarm-test.js +++ b/tests/swarm-test.js @@ -73,6 +73,18 @@ experiment('BASICS', function () { done() }) }) + + experiment('Swarm.registerHandler', function () { + test('throws when registering a protcol handler twice', function (done) { + var swarm = new Swarm() + swarm.registerHandler('/sparkles/1.1.1', function () {}) + swarm.registerHandler('/sparkles/1.1.1', function (err) { + expect(err).to.be.an.instanceOf(Error) + expect(err.message).to.be.equal('Handle for protocol already exists') + done() + }) + }) + }) }) experiment('BASE', function () {