Skip to content

Commit

Permalink
Added utils.serializeCookie()
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Jun 14, 2010
1 parent eb15df0 commit fda3014
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
32 changes: 31 additions & 1 deletion lib/connect/utils.js
Expand Up @@ -48,7 +48,7 @@ exports.parseCookie = function(str){
var key = pair.substr(0, eqlIndex).trim(),
val = pair.substr(++eqlIndex, pair.length).trim();
// Quoted values
if (val[0] === "'" || val[0] === '"') {
if (val[0] === '"') {
val = val.slice(1, -1);
}
// Only assign once
Expand All @@ -58,4 +58,34 @@ exports.parseCookie = function(str){
}
}
return obj;
};

/**
* Serialize the given object into a cookie string.
*
* @param {String} name
* @param {String} val
* @param {Object} obj
* @return {String}
* @api public
*/

exports.serializeCookie = function(name, val, obj){
var pairs = [queryString.escape(name) + '=' + queryString.escape(val)],
obj = obj || {},
keys = Object.keys(obj);
for (var i = 0, len = keys.length; i < len; ++i) {
var key = keys[i],
val = obj[key];
if (val instanceof Date) {
val = val.toUTCString();
} else if (typeof val === "boolean") {
if (val === true) {
pairs.push(key);
}
continue;
}
pairs.push(key + '=' + val);
}
return pairs.join('; ');
};
7 changes: 7 additions & 0 deletions test/connect.utils.test.js
Expand Up @@ -48,5 +48,12 @@ module.exports = {

assert.eql({ foo: 'bar', path: '/', secure: true },
utils.parseCookie('foo=bar; path=/; secure'));
},

'test serializeCookie()': function(){
assert.eql('foo=bar; path=/', utils.serializeCookie('foo', 'bar', { path: '/' }));
assert.eql('foo=bar; secure', utils.serializeCookie('foo', 'bar', { secure: true }));
assert.eql('foo=bar', utils.serializeCookie('foo', 'bar', { secure: false }));
assert.eql('foo=foo%20bar', utils.serializeCookie('foo', 'foo bar'));
}
};

0 comments on commit fda3014

Please sign in to comment.