Skip to content

Instantly share code, notes, and snippets.

@arackaf
Created January 20, 2019 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arackaf/e17da3039496b61aa61b4167e0aff3bf to your computer and use it in GitHub Desktop.
Save arackaf/e17da3039496b61aa61b4167e0aff3bf to your computer and use it in GitHub Desktop.
function syncItem(item, table, transform = item => item) {
let open = indexedDB.open("books", 1);
return new Promise(res => {
open.onsuccess = evt => {
let db = open.result;
let tran = db.transaction(table, "readwrite");
let objStore = tran.objectStore(table);
objStore.get(item._id).onsuccess = ({ target: { result: itemToUpdate } }) => {
if (!itemToUpdate) {
objStore.add(transform(item)).onsuccess = res;
} else {
Object.assign(itemToUpdate, transform(item));
objStore.put(itemToUpdate).onsuccess = res;
}
};
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment