Created
February 17, 2023 16:53
-
-
Save Santosl2/b124ddf2711e1a1c52f5f10280635a6c to your computer and use it in GitHub Desktop.
Simple Cache Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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