diff --git a/packages/core/api/index.js b/packages/core/api/index.js index cd015e79d..9b87016dd 100644 --- a/packages/core/api/index.js +++ b/packages/core/api/index.js @@ -92,7 +92,8 @@ class Database { this.ev.publish("user:upgraded", data); break; case "sync": - this.ev.publish("db:sync"); + await this.syncer.eventMerge(data); + this.ev.publish("db:refresh"); break; } }; diff --git a/packages/core/api/sync/index.js b/packages/core/api/sync/index.js index 07f8ccc40..aad1bb6bf 100644 --- a/packages/core/api/sync/index.js +++ b/packages/core/api/sync/index.js @@ -52,7 +52,7 @@ export default class Sync { return await response.json(); } - async start() { + async _performChecks() { let user = await this._db.user.get(); let token = await this._db.user.token(); if (!user || !token) throw new Error("You need to login to sync."); @@ -62,6 +62,13 @@ export default class Sync { await this._db.conflicts.check(); let lastSynced = user.notesnook.lastSynced || 0; + + return { user, lastSynced, token }; + } + + async start() { + let { user, lastSynced, token } = await this._performChecks(); + let serverResponse = await this._fetch(lastSynced, token); // we prepare local data before merging so we always have correct data @@ -82,6 +89,20 @@ export default class Sync { } } + async eventMerge(serverResponse) { + let { user, lastSynced } = await this._performChecks(); + // merge the server response + await this._merger.merge(serverResponse, lastSynced); + + // check for conflicts and throw + await this._db.conflicts.check(); + + // update our lastSynced time + if (lastSynced) { + await this._db.user.set({ notesnook: { ...user.notesnook, lastSynced } }); + } + } + async _send(data, token) { let response = await fetch(`${HOST}/sync`, { method: "POST",