Answer the question
In order to leave comments, you need to log in
How to properly cache data in a bot using redis + mongoose?
There is a bot. I want the data to be taken from the cache when requesting a user, but how best to implement this?
To do this, I made a json with redis async functions and additional functions
const redis = {
"asyncGet": promisify(client.get).bind(client),
"asyncSet": promisify(client.setex).bind(client),
"asyncKeys": promisify(client.keys).bind(client),
async allKeys() {
return await this.asyncKeys("*")
},
async get(tgId) {
let value = await this.asyncGet(tgId)
try {
value = JSON.parse( value )
} catch (e) {
await this.asyncSet(tgId, 1, "")
value = null;
}
return value
},
async set(user) {
return await this.asyncSet(user.tgId, 3 * 60, JSON.stringify(user))
}
}
async find(tgId) {
let doc;
doc = await this.redis.get(tgId)
if (doc === null) {
const doc = await userSheme.findOne({ tgId: tgId })
if ( doc !== null )
await this.redis.set(doc)
}
return doc
}
setInterval( async () => {
let keys = await redis.allKeys()
for await (let key of keys) {
const user = await redis.get(key)
if (user !== null){
console.log(user)
user.save() // user.save() is not function
}
}
}, 2 * 60 * 1000)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question