Created
January 22, 2025 12:02
-
-
Save kavinda1995/548f52d10dfda372a293032a573f49ce to your computer and use it in GitHub Desktop.
Browser Database
This file contains hidden or 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
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