Refactoring of offline handling

This commit is contained in:
Zef Hemel
2023-07-27 11:41:44 +02:00
parent 7b8d8af2c1
commit 4d0f36d475
13 changed files with 251 additions and 206 deletions
+13 -4
View File
@@ -17,14 +17,19 @@ export class FallbackSpacePrimitives implements SpacePrimitives {
fetchFileList(): Promise<FileMeta[]> {
return this.primary.fetchFileList();
}
async readFile(name: string): Promise<{ data: Uint8Array; meta: FileMeta }> {
try {
return await this.primary.readFile(name);
} catch (e) {
console.info(
`Could not read file ${name} from primary, trying fallback`,
e,
);
try {
return this.fallback.readFile(name);
} catch (fallbackError) {
console.error("Error during reaFile fallback", fallbackError);
return await this.fallback.readFile(name);
} catch (fallbackError: any) {
console.error("Error during readFile fallback", fallbackError);
// Fallback failed, so let's throw the original error
throw e;
}
@@ -34,8 +39,12 @@ export class FallbackSpacePrimitives implements SpacePrimitives {
try {
return await this.primary.getFileMeta(name);
} catch (e) {
console.info(
`Could not fetch file ${name} metadata from primary, trying fallback`,
e,
);
try {
return this.fallback.getFileMeta(name);
return await this.fallback.getFileMeta(name);
} catch (fallbackError) {
console.error("Error during getFileMeta fallback", fallbackError);
// Fallback failed, so let's throw the original error
+28 -10
View File
@@ -21,17 +21,35 @@ export class HttpSpacePrimitives implements SpacePrimitives {
options.headers = { ...options.headers, ...{ "X-Sync-Mode": "true" } };
}
const result = await fetch(url, options);
if (result.redirected) {
// Got a redirect, we'll assume this is due to invalid credentials and redirecting to an auth page
console.log(
"Got a redirect via the API so will redirect to URL",
result.url,
);
location.href = result.url;
throw new Error("Invalid credentials");
try {
const result = await fetch(url, options);
if (result.status === 503) {
throw new Error("Offline");
}
if (result.redirected) {
// Got a redirect, we'll assume this is due to invalid credentials and redirecting to an auth page
console.log(
"Got a redirect via the API so will redirect to URL",
result.url,
);
location.href = result.url;
throw new Error("Invalid credentials");
}
return result;
} catch (e: any) {
// Firefox: NetworkError when attempting to fetch resource (with SW and without)
// Safari: FetchEvent.respondWith received an error: TypeError: Load failed (service worker)
// Safari: Load failed (no service worker)
// Chrome: Failed to fetch (with service worker and without)
// Common substrings: "fetch" "load failed"
const errorMessage = e.message.toLowerCase();
if (
errorMessage.includes("fetch") || errorMessage.includes("load failed")
) {
throw new Error("Offline");
}
throw e;
}
return result;
}
async fetchFileList(): Promise<FileMeta[]> {