Last active
November 24, 2022 18:31
-
-
Save IvsonEmidio/30a0647acaa1eb7d125739de5dacf2bf to your computer and use it in GitHub Desktop.
Typescript localstorage cache manager with validity.
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
import moment from "moment"; | |
import { CacheProperties } from "../../@types/Cache"; | |
export default class CacheService { | |
public set(key: string, value: string, validityInMinutes: number = 0): boolean { | |
try { | |
const properties: CacheProperties = { | |
key, | |
value, | |
createdAt: moment().format(), | |
validityInMinutes | |
} | |
localStorage.setItem(key, JSON.stringify(properties)); | |
return true; | |
} catch { | |
return false; | |
} | |
} | |
public get<TResponse>(key: string, isJSON: boolean = false): TResponse | null { | |
const cacheValue = localStorage.getItem(key) | |
if (!cacheValue) { | |
return null | |
} | |
const cacheProperties = JSON.parse(cacheValue) as CacheProperties; | |
if (cacheProperties.validityInMinutes > 0) { | |
const isCacheValid = this.isCacheValid(cacheProperties); | |
if (!isCacheValid) { | |
return null; | |
} | |
} | |
return isJSON ? JSON.parse(cacheProperties.value) : cacheProperties.value; | |
} | |
public destroy(key: string): void { | |
return localStorage.removeItem(key); | |
} | |
private isCacheValid(properties: CacheProperties): boolean { | |
const { createdAt, validityInMinutes } = properties; | |
const diffInMinutes = moment().diff(createdAt, 'minutes'); | |
if (diffInMinutes > validityInMinutes) { | |
this.destroy(properties.key); | |
return false | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment