-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsessionStore.js
80 lines (72 loc) · 1.54 KB
/
sessionStore.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
'use strict';
const redis = require('./services/redis');
const uuid = require('node-uuid');
const SESSION_WINDOW = 60 * 20;
class SessionStore {
constructor() {
this.sessions = {};
this._redisPrefix = "cs";
}
get(id) {
return redis.getKey(id)
.then(data => {
return redis.setExpire(id, SESSION_WINDOW)
.then(() => {
return JSON.parse(data);
});
});
}
save(id, context) {
return this.get(id)
.then(session => {
session.context = context;
return redis.setKey(id, JSON.stringify(session))
.then(() => {
return redis.setExpire(id, SESSION_WINDOW);
})
.then(() => {
return context;
});
});
}
saveSession(id, session) {
return redis.setKey(id, JSON.stringify(session))
.then(() => {
return redis.setExpire(id, SESSION_WINDOW);
})
.then(() => {
return session.context;
});
}
findOrCreate(fbid) {
let newSession = false;
return redis.findFirstKey(this._redisPrefix + '*' + fbid)
.then(key => {
if (key) {
return key;
}
newSession = true;
key = this._redisPrefix + uuid.v1() + fbid;
return redis.setKey(key, JSON.stringify({fbid: fbid, context: {}}))
.then(() => {
return key;
});
})
.then(key => {
return redis.setExpire(key, SESSION_WINDOW)
.then(() => {
return redis.getKey(key)
})
.then(data => {
return JSON.parse(data);
})
.then(session => {
return {sessionId: key, newSession: newSession, session: session};
});
});
}
destroy(id) {
return redis.deleteHash(id);
}
}
module.exports = new SessionStore();