Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created October 28, 2022 04:28

Revisions

  1. semlinker created this gist Oct 28, 2022.
    31 changes: 31 additions & 0 deletions localstorage-proxy.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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);
    }
    }