wildduck/lib/user-cache.js

59 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-12-08 20:29:00 +08:00
'use strict';
class UserCache {
2018-11-23 17:06:35 +08:00
constructor(options) {
this.users = options.users;
this.redis = options.redis;
}
flush(user, callback) {
this.redis.del('cached:' + user, () => callback());
}
get(user, key, defaultValue, callback) {
this.redis.hget('cached:' + user, key, (err, value) => {
2017-12-08 20:29:00 +08:00
if (err) {
2018-11-23 17:06:35 +08:00
return callback(err);
2017-12-08 20:29:00 +08:00
}
2018-11-23 17:06:35 +08:00
if (value) {
return callback(null, Number(value));
}
this.users.collection('users').findOne(
{
_id: user
},
{
projection: {
[key]: true
}
},
(err, userData) => {
if (err) {
return callback(err);
}
if (!userData) {
return callback(null, defaultValue);
}
value = userData[key] || defaultValue;
this.redis
.multi()
.hset('cached:' + user, key, value)
.expire('cached:' + user, 3600)
.exec(err => {
if (err) {
return callback(err);
}
return callback(null, value);
});
}
);
});
}
2017-12-08 20:29:00 +08:00
}
module.exports = UserCache;