Skip to content

Commit

Permalink
[fix] Fix middleware initialization (socketio#2969)
Browse files Browse the repository at this point in the history
Fix "TypeError: Cannot convert undefined or null to object" when a
middleware is added before the engine is properly attached.
  • Loading branch information
darrachequesne authored Jun 12, 2017
1 parent 72a6509 commit 59fdbd8
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 14 deletions.
38 changes: 26 additions & 12 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,29 +244,43 @@ Server.prototype.attach = function(srv, opts){
// set origins verification
opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this);

var self = this;
if (this.sockets.fns.length > 0) {
this.initEngine(srv, opts);
return this;
}

var self = this;
var connectPacket = { type: parser.CONNECT, nsp: '/' };
this.encoder.encode(connectPacket, function (encodedPacket){
// the CONNECT packet will be merged with Engine.IO handshake,
// to reduce the number of round trips
opts.initialPacket = encodedPacket;

// initialize engine
debug('creating engine.io instance with opts %j', opts);
self.eio = engine.attach(srv, opts);
self.initEngine(srv, opts);
});
return this;
};

/**
* Initialize engine
*
* @param {Object} options passed to engine.io
* @api private
*/

// attach static file serving
if (self._serveClient) self.attachServe(srv);
Server.prototype.initEngine = function(srv, opts){
// initialize engine
debug('creating engine.io instance with opts %j', opts);
this.eio = engine.attach(srv, opts);

// Export http server
self.httpServer = srv;
// attach static file serving
if (this._serveClient) this.attachServe(srv);

// bind to engine events
self.bind(self.eio);
});
// Export http server
this.httpServer = srv;

return this;
// bind to engine events
this.bind(this.eio);
};

/**
Expand Down
6 changes: 4 additions & 2 deletions lib/namespace.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,10 @@ Namespace.prototype.initAdapter = function(){
*/

Namespace.prototype.use = function(fn){
debug('removing initial packet');
delete this.server.eio.initialPacket;
if (this.server.eio) {
debug('removing initial packet');
delete this.server.eio.initialPacket;
}
this.fns.push(fn);
return this;
};
Expand Down
13 changes: 13 additions & 0 deletions test/socket.io.js
Original file line number Diff line number Diff line change
Expand Up @@ -2268,6 +2268,19 @@ describe('socket.io', function(){
});
});
});

it('should disable the merge of handshake packets', function(done){
var srv = http();
var sio = io();
sio.use(function(socket, next){
next();
});
sio.listen(srv);
var socket = client(srv);
socket.on('connect', function(){
done();
});
});
});

describe('socket middleware', function(done){
Expand Down

0 comments on commit 59fdbd8

Please sign in to comment.