Skip to content

Instantly share code, notes, and snippets.

@arackaf
Last active January 29, 2024 23:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save arackaf/16e55868e17f59bab6495cd3186fd501 to your computer and use it in GitHub Desktop.
Save arackaf/16e55868e17f59bab6495cd3186fd501 to your computer and use it in GitHub Desktop.
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