wildduck/lib/user-cache.js

74 lines
2.1 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;
2022-07-05 16:57:57 +08:00
this.settingsHandler = options.settingsHandler;
2018-11-23 17:06:35 +08:00
}
flush(user, callback) {
this.redis.del('cached:' + user, () => callback());
}
2022-07-05 16:57:57 +08:00
getDefaultValue(defaultValue, callback) {
if (defaultValue && typeof defaultValue === 'object' && defaultValue.setting && typeof defaultValue.setting === 'string') {
this.settingsHandler
.get(defaultValue.setting)
.then(value => {
callback(null, value);
})
.catch(err => callback(err));
return;
}
callback(null, defaultValue);
}
2018-11-23 17:06:35 +08:00
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);
}
2022-07-05 16:57:57 +08:00
if (!userData || !userData[key]) {
return this.getDefaultValue(defaultValue, callback);
2018-11-23 17:06:35 +08:00
}
2022-07-05 16:57:57 +08:00
value = userData[key];
2018-11-23 17:06:35 +08:00
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;