Skip to content

Commit

Permalink
fix: auto refresh app on db crash (#1829)
Browse files Browse the repository at this point in the history
  • Loading branch information
aeharding authored Jan 31, 2025
1 parent 496556b commit a7315d9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/core/listeners/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { App } from "@capacitor/app";
import Dexie from "dexie";

import { isAppleDeviceInstallable, isNative } from "#/helpers/device";

const DB_CLOSED_STORAGE_KEY = "db-closed";

/**
* https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/354#issuecomment-1305878417
*/
if (isNative() && isAppleDeviceInstallable()) {
App.addListener("appStateChange", async (state) => {
const dbLastClosed = +(localStorage.getItem(DB_CLOSED_STORAGE_KEY) || 0);
const thirtySecondsAgo = Date.now() - 30_000;

const reloadedRecently = dbLastClosed > thirtySecondsAgo;

if (!state.isActive) return;
if (reloadedRecently) return;

console.info("Checking database integrity...");

// Fix connection Storage sometime lost (iOS)
try {
await Dexie.exists("WefwefDB");
} catch (error) {
if (!(error instanceof Error)) throw error;
if (error.name !== "UnknownError") throw error;
if (
!error.message.includes(
"Connection to Indexed Database server lost. Refresh the page to try again",
)
)
throw error;

console.info("Failed database integrity check!", error);

localStorage.setItem(DB_CLOSED_STORAGE_KEY, Date.now().toString());

window.location.reload();

throw error;
}

console.info("Passed database integrity check!");
});
}
1 change: 1 addition & 0 deletions src/core/listeners/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import HapticsListener from "./HapticsListener";

// Listeners
import "./androidSafeArea";
import "./db";
import "./ionActivatable";
import "./network/listener";
import "./statusTap";
Expand Down

0 comments on commit a7315d9

Please sign in to comment.