Skip to content

Instantly share code, notes, and snippets.

@GautamPanickar
Last active December 13, 2020 07:05
Show Gist options
  • Save GautamPanickar/5471197bdcd80696c0377720a17e8e01 to your computer and use it in GitHub Desktop.
Save GautamPanickar/5471197bdcd80696c0377720a17e8e01 to your computer and use it in GitHub Desktop.
/**
* Here also, all objects are added in a single transaction, with the difference being, before addition,
* the object is checked for equality. If same object exists, then update is performed, otherwise addition is proceeded.
*/
connection.onsuccess = (e) => {
var db = e.target.result;
let startedTime = Date.now();
console.log(`Started on - ${startedTime}`);
var transaction = db.transaction('contacts', 'readwrite');
var store = transaction.objectStore('contacts');
var newContactsToAdd = contacts;
var allContactsReq = store.getAll();
allContactsReq.onsuccess = (evt) => {
const existingContacts = evt.target.result;
const commonContactIds = [];
var updateTrans = db.transaction('contacts', 'readwrite');
var updateStore = updateTrans.objectStore('contacts');
var deleteTrans = db.transaction('contacts', 'readwrite');
var deleteStore = deleteTrans.objectStore('contacts');
existingContacts.forEach(contact => {
// Check if the same contact is in the new contacts list
const cIndex = newContactsToAdd.findIndex(c => c.id === contact.id);
if (cIndex >= 0) {
const contactToUpdate = newContactsToAdd.splice(cIndex, 1);
const req = updateStore.put(contactToUpdate, 'id');
req.onerror = (evt) => {
console.log(`Error on updating contact`);
evt.preventDefault();
};
req.onsuccess = (evt) => {
console.log(`Update Timestamp - ${Date.now()}`);
};
commonContactIds.push(contactToUpdate.id);
}else {
// These contacts will have to be removed
console.log('Id to delete -' + contact.id);
const req = deleteStore.delete(contact.id);
req.onerror = (evt) => {
console.log(`Error on deleting contact`);
evt.preventDefault();
};
req.onsuccess = (evt) => {
console.log(`Delete Timestamp - ${Date.now()}`);
};
}
});
// Add new contacts
newContactsToAdd.forEach(contact => {
const req = updateStore.add(contact, contact.id);
req.onerror = (evt) => {
console.log(`Error on adding contact`);
evt.preventDefault();
};
req.onsuccess = (evt) => {
console.log(`Add Timestamp - ${Date.now()}`);
};
});
};
allContactsReq.onerror = (evt) => {
console.log(`Could not fetch exisitng contacts`);
store.clear();
// Add all contacts
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment