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.

jar.js 1.4 KiB

12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*!
  2. * Tobi - CookieJar
  3. * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var url = require('url');
  10. /**
  11. * Initialize a new `CookieJar`.
  12. *
  13. * @api private
  14. */
  15. var CookieJar = exports = module.exports = function CookieJar() {
  16. this.cookies = [];
  17. };
  18. /**
  19. * Add the given `cookie` to the jar.
  20. *
  21. * @param {Cookie} cookie
  22. * @api private
  23. */
  24. CookieJar.prototype.add = function(cookie){
  25. this.cookies = this.cookies.filter(function(c){
  26. // Avoid duplication (same path, same name)
  27. return !(c.name == cookie.name && c.path == cookie.path);
  28. });
  29. this.cookies.push(cookie);
  30. };
  31. /**
  32. * Get cookies for the given `req`.
  33. *
  34. * @param {IncomingRequest} req
  35. * @return {Array}
  36. * @api private
  37. */
  38. CookieJar.prototype.get = function(req){
  39. var path = url.parse(req.url).pathname
  40. , now = new Date
  41. , specificity = {};
  42. return this.cookies.filter(function(cookie){
  43. if (0 == path.indexOf(cookie.path) && now < cookie.expires
  44. && cookie.path.length > (specificity[cookie.name] || 0))
  45. return specificity[cookie.name] = cookie.path.length;
  46. });
  47. };
  48. /**
  49. * Return Cookie string for the given `req`.
  50. *
  51. * @param {IncomingRequest} req
  52. * @return {String}
  53. * @api private
  54. */
  55. CookieJar.prototype.cookieString = function(req){
  56. var cookies = this.get(req);
  57. if (cookies.length) {
  58. return cookies.map(function(cookie){
  59. return cookie.name + '=' + cookie.value;
  60. }).join('; ');
  61. }
  62. };