Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function fullSync(page = 1) {
let open = indexedDB.open("books", 1);
// Set up the database schema
open.onsuccess = evt => {
let db = open.result;
fullSyncPage(db, 1);
};
}
function fullSyncPage(db, page) {
let pageSize = 50;
doFetch("/book/offlineSync", { page, pageSize })
.then(resp => resp.json())
.then(resp => {
if (!resp.books) return;
let books = resp.books;
let i = 0;
putNext();
function putNext() {
if (i < pageSize) {
let book = books[i++];
if (!book) {
loadDone(db);
return;
}
let transaction = db.transaction("books", "readwrite");
let booksStore = transaction.objectStore("books");
booksStore.add(Object.assign(book, { imgSync: 0 })).onsuccess = putNext;
} else {
if (books.length > pageSize) {
fullSyncPage(db, page + 1);
} else {
loadDone(db);
}
}
}
});
}
function loadDone(db) {
let transaction = db.transaction("syncInfo", "readwrite");
let syncInfoStore = transaction.objectStore("syncInfo");
let req = syncInfoStore.get(1);
req.onsuccess = ({ target: { result } }) => {
Object.assign(result, { lastLoad: +new Date(), lastLoadStarted: null });
syncInfoStore.put(result);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.