Created
February 10, 2018 12:14
-
-
Save mskasal/842f853ea653d1748bf76c1f4a9fd6d0 to your computer and use it in GitHub Desktop.
Create and manage localStorage collection asynchronously.
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
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