Skip to content

Instantly share code, notes, and snippets.

@IvsonEmidio
Last active November 24, 2022 18:31
Show Gist options
  • Save IvsonEmidio/30a0647acaa1eb7d125739de5dacf2bf to your computer and use it in GitHub Desktop.
Save IvsonEmidio/30a0647acaa1eb7d125739de5dacf2bf to your computer and use it in GitHub Desktop.
Typescript localstorage cache manager with validity.
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;
}
}
@IvsonEmidio
Copy link
Author

Needs momentJS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment