Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created October 28, 2022 04:28
Show Gist options
  • Save semlinker/696b631c7ef050e4b2ce060c9162261d to your computer and use it in GitHub Desktop.
Save semlinker/696b631c7ef050e4b2ce060c9162261d to your computer and use it in GitHub Desktop.
LocalStorageProxy
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