Skip to content

Instantly share code, notes, and snippets.

@mskasal
Created February 10, 2018 12:14
Show Gist options
  • Save mskasal/842f853ea653d1748bf76c1f4a9fd6d0 to your computer and use it in GitHub Desktop.
Save mskasal/842f853ea653d1748bf76c1f4a9fd6d0 to your computer and use it in GitHub Desktop.
Create and manage localStorage collection asynchronously.
const asyncLocalStorage = {
createCollection: (collectionName, data) => Promise.resolve().then(() => {
if (!(data instanceof Object)) {
throw Error('Local storage collection can be only valid JSON.');
}
return localStorage.setItem(collectionName, JSON.stringify(data));
}),
getCollection: collectionName => Promise.resolve().then(() =>
localStorage.getItem(collectionName)),
setItem: (key, value, collectionName) => Promise.resolve()
.then(() => localStorage.getItem(collectionName))
.then(collectionData => JSON.parse(collectionData))
.then((parsed) => { const newData = Object(parsed); newData[key] = value; return newData; })
.then(newData => localStorage.setItem(collectionName, JSON.stringify(newData))),
getItem: (key, collectionName) => Promise.resolve()
.then(() => localStorage.getItem(collectionName))
.then(collectionData => JSON.parse(collectionData)[key]),
removeItem: (key, value, collectionName) => Promise.resolve()
.then(() => localStorage.getItem(collectionName))
.then(collectionData => JSON.parse(collectionData))
.then((parsed) => { const newData = Object(parsed); delete newData[key]; return newData; })
.then(newData => localStorage.setItem(collectionName, JSON.stringify(newData))),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment