-
-
Save okparaa/a4b01df40e843fd18d2355e09b9109e0 to your computer and use it in GitHub Desktop.
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
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