Skip to content

Instantly share code, notes, and snippets.

@Santosl2
Created February 17, 2023 16:53
Show Gist options
  • Select an option

  • Save Santosl2/b124ddf2711e1a1c52f5f10280635a6c to your computer and use it in GitHub Desktop.

Select an option

Save Santosl2/b124ddf2711e1a1c52f5f10280635a6c to your computer and use it in GitHub Desktop.
Simple Cache Class
export class CacheMap {
private cache: Map<string, Cache>;
private expiration_time: number; // Tempo de expiração em segundos
constructor(expiration?: number) {
this.cache = new Map();
this.expiration_time = expiration || 60;
}
get(key: string) {
const value = this.cache.get(key);
if (value) {
const now = new Date().getTime();
if (value.expiresIn < now) {
this.invalidate(key);
return null;
}
return value;
}
return null;
}
set(key: string, value: Cache) {
const exp_time = new Date().getTime() + this.expiration_time * 1000;
this.cache.set(key, {
...value,
expiresIn: exp_time,
});
}
invalidate(key: string) {
this.cache.delete(key);
}
invalidateAllByPrefix(prefix: string) {
this.cache.forEach((value, key) => {
if (key.startsWith(prefix)) {
this.cache.delete(key);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment