koel/resources/assets/js/services/cache.ts

59 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-07-25 13:25:27 +00:00
const DEFAULT_EXPIRATION_TIME = 1000 * 60 * 60 * 24 // 1 day
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
export class Cache {
private storage = new Map<any, {
expires: number,
2022-07-04 10:38:06 +00:00
value: any
2022-07-25 13:25:27 +00:00
}>()
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
private static normalizeKey (key: any) {
return typeof key === 'object' ? JSON.stringify(key) : key
}
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
public has (key: any) {
return this.hit(Cache.normalizeKey(key))
}
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
public get<T> (key: any) {
return this.storage.get(Cache.normalizeKey(key))?.value as T
}
2022-07-25 13:25:27 +00:00
public set (key: any, value: any, seconds: number = DEFAULT_EXPIRATION_TIME) {
this.storage.set(Cache.normalizeKey(key), {
2022-07-04 10:38:06 +00:00
value,
2022-07-25 13:25:27 +00:00
expires: Date.now() + seconds * 1000
2022-07-04 10:38:06 +00:00
})
2022-07-25 13:25:27 +00:00
}
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
public hit (key: any) {
return !this.miss(Cache.normalizeKey(key))
}
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
public miss (key: any) {
key = Cache.normalizeKey(key)
2022-07-04 10:38:06 +00:00
if (!this.storage.has(key)) return true
2022-07-25 13:25:27 +00:00
const { expires } = this.storage.get(key)!
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
if (expires < Date.now()) {
2022-07-04 10:38:06 +00:00
this.storage.delete(key)
return true
}
return false
2022-07-25 13:25:27 +00:00
}
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
public remove (key: any) {
this.storage.delete(Cache.normalizeKey(key))
}
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
async remember<T> (key: any, resolver: Closure, seconds: number = DEFAULT_EXPIRATION_TIME) {
key = Cache.normalizeKey(key)
2022-07-04 10:38:06 +00:00
2022-07-25 13:25:27 +00:00
this.hit(key) || this.set(key, await resolver(), seconds)
return this.get<T>(key)
2022-07-04 10:38:06 +00:00
}
}
2022-07-25 13:25:27 +00:00
export const cache = new Cache()