From ebecd2a30d10814afd8bef22c4eb4ac017905f8a Mon Sep 17 00:00:00 2001 From: Cal Paterson Date: Fri, 18 Dec 2020 16:19:22 +0000 Subject: [PATCH] Fix two issues around not checking for bad server responses Firstly, correctly set last sync status when told not to sync by server Secondly, check status code before proceeding --- src/extension/src/quarchive-sync.ts | 30 ++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/extension/src/quarchive-sync.ts b/src/extension/src/quarchive-sync.ts index 42717f0..064b433 100644 --- a/src/extension/src/quarchive-sync.ts +++ b/src/extension/src/quarchive-sync.ts @@ -32,20 +32,38 @@ async function getHTTPConfig(): Promise> { let gettingURL = await browser.storage.sync.get("APIURL"); const returnValue = [gettingURL.APIURL, gettingUsername.username, gettingKey.APIKey]; if (returnValue.includes(undefined)) { - throw new NoConfigurationError(); + throw new NoConfigurationError("no or missing configuration"); } else { return returnValue; } } class NoConfigurationError extends Error { - constructor(message?: string) { + constructor(message: string) { super(message); Object.setPrototypeOf(this, new.target.prototype); this.name = NoConfigurationError.name } } +class BadServerResponseError extends Error { + response: Response + constructor(message: string, response: Response) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + this.name = BadServerResponseError.name + this.response = response + } +} + +function throwForStatus(response: Response): void { + if(!response.ok){ + console.warn("got %d from server", response.status); + throw new BadServerResponseError(`bad response: (${response.status})`, response); + } +} + + async function setLastFullSyncResult(result: SyncResult): Promise { const storable = { "status": result.status, @@ -309,6 +327,7 @@ async function callSyncAPI(bookmark: Bookmark): Promise> { }, body: sync_body, }); + throwForStatus(response); const jsonlines = await response.text() let returnValue = []; @@ -351,6 +370,7 @@ async function callFullSyncAPI(bookmarks: Array): Promise { "Quarchive-ClientID": clientID, } }); + throwForStatus(response); const json = await response.json() - return json.should_sync; + return json.should_sync === true; } export async function fullSync(force: boolean = false): Promise { @@ -404,13 +425,12 @@ export async function fullSync(force: boolean = false): Promise { // status back if (!force && !await shouldSync()) { console.log("no need to sync yet") - status = oldStatus; + setLastFullSyncResult(oldStatus); } else { if (force) { console.warn("forcing sync"); } - // Then retrieve the server's point of view const bookmarksFromServer = await callFullSyncAPI(await allBookmarksFromLocalDb());