H
H
Hanry6542020-12-30 20:25:10
Redis
Hanry654, 2020-12-30 20:25:10

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))
  }
}

The user writes ->
If there is his document in the cache, he uses
No document, a request is made, we return and enter the document immediately into the cache for 3 minutes
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
}

I got stuck on the fact that I did setInterval, which every 2 minutes, puts the user's changes into the database, so as not to save the document every time after the command.
But the problem is that JSON.stringify() doesn't string functions and it's not possible to save the document.
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)


Maybe there are other implementation methods that are much better than this shit code?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question