forked from tj/connect-redis
/
index.js
103 lines (87 loc) · 1.95 KB
/
index.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
/*!
* Connect - Redis
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var sys = require('sys'),
Store = require('connect/middleware/session/store'),
redis = require('./support/redis/lib/redis-client');
/**
* 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 = new redis.createClient(options.port, options.host, options);
};
sys.inherits(RedisStore, Store);
/**
* Attempt to fetch session by the given `hash`.
*
* @param {String} hash
* @param {Function} fn
* @api public
*/
RedisStore.prototype.get = function(hash, fn){
this.client.get(hash, function(err, data){
try {
fn(null, data
? JSON.parse(data.toString())
: data);
} catch (err) {
fn(err);
}
});
};
/**
* Commit the given `sess` object associated with the given `hash`.
*
* @param {String} hash
* @param {Session} sess
* @param {Function} fn
* @api public
*/
RedisStore.prototype.set = function(hash, sess, fn){
var self = this;
try {
this.client.set(hash, JSON.stringify(sess), function(){
self.client.expire(hash, self.maxAge);
fn && fn.apply(this, arguments);
});
} catch (err) {
fn && fn(err);
}
};
/**
* Destroy the session associated with the given `hash`.
*
* @param {String} hash
* @api public
*/
RedisStore.prototype.destroy = function(hash, fn){
this.client.del(hash, 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);
};