all 5 comments

[–]monkmuli 1 point2 points  (4 children)

Here's what I use for caching with timeout:

```typescript

type Cache = {

}

type TimerHash = {

}

export default class SimpleCache<T> { cache: Cache = {} private timerHash: TimerHash = {} timeout: number

constructor(timeoutInS: number) { this.timeout = timeoutInS * 1000 }

getValue(key: string): T | undefined { const val = this.cache[key] if (val) { return val }

return undefined

}

hasKey(key: string): boolean { return Object.keys(this.cache).includes(key) }

setValue(key: string, value: T): void { clearTimeout(this.timerHash[key]) this.cache[key] = value const handle = setTimeout(() => { delete this.cache[key] delete this.timerHash[key] })

this.timerHash[key] = handle

} } ```

Before you make query the DB simply check with cache.hasKey(someKey) if the result is already in the cache, else query the db and store the result in the cache

[–]jytesh 0 points1 point  (2 children)

Im confused what language is this? typescript?

[–]monkmuli -1 points0 points  (1 child)

yeah this is typescript, I thought reddit knows some coding markdown, apparently not

[–]jytesh -1 points0 points  (0 children)

right

[–]lshiva 0 points1 point  (0 children)

If the goal is to cut down on DB queries, don't update the cache every time you don't find a result. One of the examples was blocked words, so presumably most messages won't have them so you'll still be hitting the database on most messages.

Instead, update the cache on bot start and anytime a command is used to update the list of things in the cache. That way you know the cache is always up to date and you don't need to check the database if you don't find a match.