From 1053dbe9a604086678b18b8ad62b49d008a50482 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Tue, 12 Sep 2017 16:09:53 +0200 Subject: [PATCH] Fixes #10 - Do not the same cookie multiple times. Now using a map rather than a list to store cookies by name. --- cometd-nodejs-client.js | 26 ++++++++++++++++---------- test/cookies.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 10 deletions(-) diff --git a/cometd-nodejs-client.js b/cometd-nodejs-client.js index 334fc99..4bdcc2f 100644 --- a/cometd-nodejs-client.js +++ b/cometd-nodejs-client.js @@ -52,14 +52,16 @@ module.exports = { if (!cookieStore) { cookieStore = _cookieStore; } - var list = cookieStore[_config.hostname]; - if (list) { + var jar = cookieStore[_config.hostname]; + if (jar) { var cookies = ''; - for (var i = 0; i < list.length; ++i) { - if (i > 0) { - cookies += '; '; + for (var name in jar) { + if (jar.hasOwnProperty(name)) { + if (cookies) { + cookies += '; '; + } + cookies += jar[name]; } - cookies += list[i]; } if (cookies) { _config.headers['Cookie'] = cookies; @@ -84,11 +86,15 @@ module.exports = { var cookie = parts[0]; var host = _config.hostname; - var list = cookieStore[host]; - if (list === undefined) { - cookieStore[host] = list = []; + var jar = cookieStore[host]; + if (jar === undefined) { + cookieStore[host] = jar = {}; + } + + var equal = cookie.indexOf('='); + if (equal > 0) { + jar[cookie.substring(0, equal)] = cookie; } - list.push(cookie); } } } diff --git a/test/cookies.js b/test/cookies.js index 44cfe49..097e4df 100644 --- a/test/cookies.js +++ b/test/cookies.js @@ -144,4 +144,43 @@ describe('cookies', function() { xhrA1.send(); }); }); + + it('handles cookie sent multiple times', function(done) { + var cookieName = 'a'; + var cookieValue = 'b'; + var cookie = cookieName + '=' + cookieValue; + _server = http.createServer(function(request, response) { + if (/\/verify$/.test(request.url)) { + assert.strictEqual(request.headers['cookie'], cookie); + response.end(); + } else { + response.setHeader('Set-Cookie', cookie); + response.end(); + } + }); + _server.listen(0, 'localhost', function() { + var port = _server.address().port; + console.log('listening on localhost:' + port); + + var xhr1 = new window.XMLHttpRequest(); + xhr1.open('GET', 'http://localhost:' + port + '/1'); + xhr1.onload = function() { + assert.strictEqual(xhr1.status, 200); + var xhr2 = new window.XMLHttpRequest(); + xhr2.open('GET', 'http://localhost:' + port + '/2'); + xhr2.onload = function() { + assert.strictEqual(xhr2.status, 200); + var xhr3 = new window.XMLHttpRequest(); + xhr3.open('GET', 'http://localhost:' + port + '/verify'); + xhr3.onload = function() { + assert.strictEqual(xhr1.status, 200); + done(); + }; + xhr3.send(); + }; + xhr2.send(); + }; + xhr1.send(); + }); + }); });