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.

129 lines
2.3 KiB

  1. /*!
  2. * Connect - session - MemoryStore
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var Store = require('./store');
  11. /**
  12. * Initialize a new `MemoryStore`.
  13. *
  14. * @api public
  15. */
  16. var MemoryStore = module.exports = function MemoryStore() {
  17. this.sessions = {};
  18. };
  19. /**
  20. * Inherit from `Store.prototype`.
  21. */
  22. MemoryStore.prototype.__proto__ = Store.prototype;
  23. /**
  24. * Attempt to fetch session by the given `sid`.
  25. *
  26. * @param {String} sid
  27. * @param {Function} fn
  28. * @api public
  29. */
  30. MemoryStore.prototype.get = function(sid, fn){
  31. var self = this;
  32. process.nextTick(function(){
  33. var expires
  34. , sess = self.sessions[sid];
  35. if (sess) {
  36. sess = JSON.parse(sess);
  37. expires = 'string' == typeof sess.cookie.expires
  38. ? new Date(sess.cookie.expires)
  39. : sess.cookie.expires;
  40. if (!expires || new Date < expires) {
  41. fn(null, sess);
  42. } else {
  43. self.destroy(sid, fn);
  44. }
  45. } else {
  46. fn();
  47. }
  48. });
  49. };
  50. /**
  51. * Commit the given `sess` object associated with the given `sid`.
  52. *
  53. * @param {String} sid
  54. * @param {Session} sess
  55. * @param {Function} fn
  56. * @api public
  57. */
  58. MemoryStore.prototype.set = function(sid, sess, fn){
  59. var self = this;
  60. process.nextTick(function(){
  61. self.sessions[sid] = JSON.stringify(sess);
  62. fn && fn();
  63. });
  64. };
  65. /**
  66. * Destroy the session associated with the given `sid`.
  67. *
  68. * @param {String} sid
  69. * @api public
  70. */
  71. MemoryStore.prototype.destroy = function(sid, fn){
  72. var self = this;
  73. process.nextTick(function(){
  74. delete self.sessions[sid];
  75. fn && fn();
  76. });
  77. };
  78. /**
  79. * Invoke the given callback `fn` with all active sessions.
  80. *
  81. * @param {Function} fn
  82. * @api public
  83. */
  84. MemoryStore.prototype.all = function(fn){
  85. var arr = []
  86. , keys = Object.keys(this.sessions);
  87. for (var i = 0, len = keys.length; i < len; ++i) {
  88. arr.push(this.sessions[keys[i]]);
  89. }
  90. fn(null, arr);
  91. };
  92. /**
  93. * Clear all sessions.
  94. *
  95. * @param {Function} fn
  96. * @api public
  97. */
  98. MemoryStore.prototype.clear = function(fn){
  99. this.sessions = {};
  100. fn && fn();
  101. };
  102. /**
  103. * Fetch number of sessions.
  104. *
  105. * @param {Function} fn
  106. * @api public
  107. */
  108. MemoryStore.prototype.length = function(fn){
  109. fn(null, Object.keys(this.sessions).length);
  110. };