2 /// Serialize the a name value pair into a cookie string suitable for
3 /// http headers. An optional options object specified cookie parameters
5 /// serialize('foo', 'bar', { httpOnly: true })
6 /// => "foo=bar; httpOnly"
8 /// @param {String} name
9 /// @param {String} val
10 /// @param {Object} options
12 var serialize = function(name, val, opt){
14 var enc = opt.encode || encode;
15 var pairs = [name + '=' + enc(val)];
17 if (null != opt.maxAge) {
18 var maxAge = opt.maxAge - 0;
19 if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
20 pairs.push('Max-Age=' + maxAge);
23 if (opt.domain) pairs.push('Domain=' + opt.domain);
24 if (opt.path) pairs.push('Path=' + opt.path);
25 if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString());
26 if (opt.httpOnly) pairs.push('HttpOnly');
27 if (opt.secure) pairs.push('Secure');
29 return pairs.join('; ');
32 /// Parse the given cookie header string into an object
33 /// The object has the various cookies as keys(names) => values
34 /// @param {String} str
36 var parse = function(str, opt) {
39 var pairs = str.split(/; */);
40 var dec = opt.decode || decode;
42 pairs.forEach(function(pair) {
43 var eq_idx = pair.indexOf('=')
45 // skip things that don't look like key=value
50 var key = pair.substr(0, eq_idx).trim()
51 var val = pair.substr(++eq_idx, pair.length).trim();
55 val = val.slice(1, -1);
59 if (undefined == obj[key]) {
71 var encode = encodeURIComponent;
72 var decode = decodeURIComponent;
74 module.exports.serialize = serialize;
75 module.exports.parse = parse;