Skip to content

Instantly share code, notes, and snippets.

@kavinda1995
Created January 22, 2025 12:02
Show Gist options
  • Save kavinda1995/548f52d10dfda372a293032a573f49ce to your computer and use it in GitHub Desktop.
Save kavinda1995/548f52d10dfda372a293032a573f49ce to your computer and use it in GitHub Desktop.
Browser Database
const browserDatabase = {
/**
* Loads data from browser storage
*/
getItem<T>(location: string): T | null {
try {
const entryObject = JSON.parse(localStorage.getItem(location) || '');
const { data, expiration, createdAt } = entryObject;
const MILLISECONDS_TO_SECONDS = 1000;
if (expiration && Date.now() - createdAt > expiration * MILLISECONDS_TO_SECONDS) {
localStorage.removeItem(location);
return null;
}
return data;
} catch {
return null;
}
},
/**
* Save data to local storage
*/
setItem<T>(location: string, data: T, expiration?: number) {
localStorage.setItem(location, JSON.stringify({
data,
expiration,
createdAt: Date.now()
}));
},
/**
* Delete item from local storage
*/
deleteItem(location: string) {
localStorage.removeItem(location);
}
};
export default browserDatabase;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment