-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmy-connect-redis.js
120 lines (99 loc) · 2.15 KB
/
my-connect-redis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*!
* Connect - Redis
* Copyright(c) 2010 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Store = require('connect').session.Store
, redis = require('redis');
/**
* One day in seconds.
*/
var oneDay = 86400;
/**
* Initialize RedisStore with the given `options`.
*
* @param {Object} options
* @api public
*/
var RedisStore = module.exports = function RedisStore(options) {
options = options || {};
Store.call(this, options);
this.client = redis.createClient(options.port, options.host);
var dbAuth = function(client) { client.auth(options.password); }
this.client.addListener('connected', dbAuth);
this.client.addListener('reconnected', dbAuth);
dbAuth(this.client);
};
/**
* Inherit from `Store`.
*/
RedisStore.prototype.__proto__ = Store.prototype;
/**
* Attempt to fetch session by the given `sid`.
*
* @param {String} sid
* @param {Function} fn
* @api public
*/
RedisStore.prototype.get = function(sid, fn){
this.client.get(sid, function(err, data){
try {
if (!data) return fn();
fn(null, JSON.parse(data.toString()));
} catch (err) {
fn(err);
}
});
};
/**
* Commit the given `sess` object associated with the given `sid`.
*
* @param {String} sid
* @param {Session} sess
* @param {Function} fn
* @api public
*/
RedisStore.prototype.set = function(sid, sess, fn){
try {
var maxAge = sess.cookie.maxAge
, ttl = 'number' == typeof maxAge
? maxAge / 1000 | 0
: oneDay
, sess = JSON.stringify(sess);
this.client.setex(sid, ttl, sess, function(){
fn && fn.apply(this, arguments);
});
} catch (err) {
fn && fn(err);
}
};
/**
* Destroy the session associated with the given `sid`.
*
* @param {String} sid
* @api public
*/
RedisStore.prototype.destroy = function(sid, fn){
this.client.del(sid, fn);
};
/**
* Fetch number of sessions.
*
* @param {Function} fn
* @api public
*/
RedisStore.prototype.length = function(fn){
this.client.dbsize(fn);
};
/**
* Clear all sessions.
*
* @param {Function} fn
* @api public
*/
RedisStore.prototype.clear = function(fn){
this.client.flushdb(fn);
};