fix: do not allow multiple concurrent syncs

This commit is contained in:
thecodrr
2021-08-10 11:59:26 +05:00
parent 890d0f5076
commit 1ca53f939e

View File

@@ -42,6 +42,7 @@ export default class Sync {
this._collector = new Collector(this._db);
this._merger = new Merger(this._db);
this._tokenManager = new TokenManager(this._db);
this._isSyncing = false;
}
async _fetch(lastSynced, token) {
@@ -52,6 +53,7 @@ export default class Sync {
}
async _performChecks() {
if (this._isSyncing) throw new Error("Sync already running.");
let lastSynced = (await this._db.context.read("lastSynced")) || 0;
let token = await this._tokenManager.getAccessToken();
if (!token) throw new Error("You need to login to sync.");
@@ -65,9 +67,11 @@ export default class Sync {
async start(full, force) {
if (force) await this._db.context.write("lastSynced", 0);
let { lastSynced, token } = await this._performChecks();
try {
this._isSyncing = true;
if (full) var serverResponse = await this._fetch(lastSynced, token);
// we prepare local data before merging so we always have correct data
@@ -88,6 +92,11 @@ export default class Sync {
if (lastSynced) {
await this._db.context.write("lastSynced", lastSynced);
}
} catch (e) {
throw e;
} finally {
this._isSyncing = false;
}
}
async eventMerge(serverResponse) {