-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconversation.js
41 lines (34 loc) · 1.3 KB
/
conversation.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
const redisConf = require('config').get('redis');
const Promise = require('bluebird');
const waiting = require('asyncawait/await');
const async = require('asyncawait/async');
const redis = require('redis');
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);
const redisClient = redis.createClient(redisConf);
const sessionPrefix = 'mafueng-user:';
const _buildKey = (userid) => sessionPrefix + userid;
module.exports = (sessionMaxLength) => { // eslint-disable-line arrow-body-style
return {
getContext: async((userid) => {
const context = waiting(redisClient.getAsync(_buildKey(userid)));
console.log(`Get context from store ${context}`);
if (context) {
const contextJSON = JSON.parse(context);
if ((new Date()).getTime() - contextJSON.firstReceived < sessionMaxLength) {
return contextJSON;
}
console.log(`Previous session discarded: ${context}`);
// Use previous language preference
return { url: contextJSON.url };
}
return {};
}),
updateContext: async((userid, context) => {
const res = waiting(redisClient.setexAsync(
[_buildKey(userid), sessionMaxLength, JSON.stringify(context)])
);
console.log(`Update context ${userid}: ${res}`);
}),
};
};