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