Created
October 28, 2022 04:28
-
-
Save semlinker/696b631c7ef050e4b2ce060c9162261d to your computer and use it in GitHub Desktop.
LocalStorageProxy
This file contains 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
type CacheItem = { | |
now: number; | |
value: string; | |
maxAge: number; | |
}; | |
class LocalStorageProxy { | |
setItem(key: string, value: unknown, maxAge: number = 0) { | |
localStorage.setItem( | |
key, | |
JSON.stringify({ | |
value, | |
maxAge, | |
now: Date.now(), | |
}) | |
); | |
} | |
getItem(key: string): string | null { | |
const item = localStorage.getItem(key); | |
if (!item) return null; | |
const cachedItem = JSON.parse(item) as CacheItem; | |
const isExpired = Date.now() - cachedItem.now > cachedItem.maxAge; | |
isExpired && this.removeItem(key); | |
return isExpired ? null : cachedItem.value; | |
} | |
removeItem(key: string): void { | |
localStorage.removeItem(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment