Skip to content

Instantly share code, notes, and snippets.

@dipanjanpanja6
Created August 11, 2023 10:57
Show Gist options
  • Save dipanjanpanja6/4333dda7e2210e644f45fd2d95621db7 to your computer and use it in GitHub Desktop.
Save dipanjanpanja6/4333dda7e2210e644f45fd2d95621db7 to your computer and use it in GitHub Desktop.
LocalCacheService
import { DateTime } from 'luxon'
import Logger from '@ioc:Adonis/Core/Logger'
class LocalCacheService {
private cache: { [key: string]: any } = {}
timerRef: NodeJS.Timer
constructor() {
this.timerRef = setInterval(() => {
Logger.trace('Auto cleaning expired item')
this.cleanExpired()
}, 60 * 60 * 1000)
}
get(key: string) {
const data = this.cache[key]
if (!data) return
if (DateTime.fromMillis(data.created_at).diffNow().toMillis() < -data.expire) {
this.delete(key)
return
}
return data.value || true
}
set(key: string, value: any, expire = 60) {
return (this.cache[key] = { value, expire, created_at: DateTime.now().toMillis() })
}
getSet(key: string, value: any, setIfValue?: boolean) {
const cachedValue = this.get(key)
if (setIfValue && !cachedValue) return cachedValue
this.set(key, value)
return cachedValue
}
delete(key: string) {
return delete this.cache[key]
}
cleanExpired() {
Object.entries(this.cache).forEach(([key, data]) => {
if (DateTime.fromMillis(data.created_at).diffNow().toMillis() < -data.expire) {
this.delete(key)
}
})
}
}
export default new LocalCacheService()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment