-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession-manager.js
61 lines (49 loc) · 1.26 KB
/
session-manager.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
/*jslint node: true, indent: 2, sloppy: true, white: true, vars: true */
var Q = require('q');
// TODO: use redis or something else to store session state
module.exports = (function () {
var self = {};
var sessions = {};
// 5 minute lifetime on sessions.
var lifetime = 5 * 60 * 1000;
// context.type
// context.choices
// context.actions
// context.params
function makeEntry(caller, context) {
return {
context: context,
caller: caller,
time: Date.now()
};
}
// Set and forget
self.save = function (caller, context) {
sessions[caller] = makeEntry(caller, context);
};
// Use a Deferred. We reserve the right go to asynchronous.
self.get = function (caller) {
var def = Q.defer();
if (sessions.hasOwnProperty(caller)) {
def.resolve(sessions[caller]);
} else {
def.resolve(null);
}
return def.promise;
};
// Clean the old sessions.
setInterval(function () {
var caller;
var entry;
var now = Date.now();
for (caller in sessions) {
if (sessions.hasOwnProperty(caller)) {
entry = sessions[caller];
if ((entry.time + lifetime) < now) {
delete sessions[caller];
}
}
}
}, 30 * 1000); // 30 seconds.
return self;
}());