You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.0 KiB

8 years ago
  1. /// Serialize the a name value pair into a cookie string suitable for
  2. /// http headers. An optional options object specified cookie parameters
  3. ///
  4. /// serialize('foo', 'bar', { httpOnly: true })
  5. /// => "foo=bar; httpOnly"
  6. ///
  7. /// @param {String} name
  8. /// @param {String} val
  9. /// @param {Object} options
  10. /// @return {String}
  11. var serialize = function(name, val, opt){
  12. opt = opt || {};
  13. var enc = opt.encode || encode;
  14. var pairs = [name + '=' + enc(val)];
  15. if (null != opt.maxAge) {
  16. var maxAge = opt.maxAge - 0;
  17. if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
  18. pairs.push('Max-Age=' + maxAge);
  19. }
  20. if (opt.domain) pairs.push('Domain=' + opt.domain);
  21. if (opt.path) pairs.push('Path=' + opt.path);
  22. if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString());
  23. if (opt.httpOnly) pairs.push('HttpOnly');
  24. if (opt.secure) pairs.push('Secure');
  25. return pairs.join('; ');
  26. };
  27. /// Parse the given cookie header string into an object
  28. /// The object has the various cookies as keys(names) => values
  29. /// @param {String} str
  30. /// @return {Object}
  31. var parse = function(str, opt) {
  32. opt = opt || {};
  33. var obj = {}
  34. var pairs = str.split(/; */);
  35. var dec = opt.decode || decode;
  36. pairs.forEach(function(pair) {
  37. var eq_idx = pair.indexOf('=')
  38. // skip things that don't look like key=value
  39. if (eq_idx < 0) {
  40. return;
  41. }
  42. var key = pair.substr(0, eq_idx).trim()
  43. var val = pair.substr(++eq_idx, pair.length).trim();
  44. // quoted values
  45. if ('"' == val[0]) {
  46. val = val.slice(1, -1);
  47. }
  48. // only assign once
  49. if (undefined == obj[key]) {
  50. try {
  51. obj[key] = dec(val);
  52. } catch (e) {
  53. obj[key] = val;
  54. }
  55. }
  56. });
  57. return obj;
  58. };
  59. var encode = encodeURIComponent;
  60. var decode = decodeURIComponent;
  61. module.exports.serialize = serialize;
  62. module.exports.parse = parse;