Skip to content

Commit

Permalink
Merge pull request #2756 from daostack/cw-master-db-remove
Browse files Browse the repository at this point in the history
Db persistance remove
  • Loading branch information
MeyerPV authored Oct 28, 2024
2 parents 532adf7 + 240f6e0 commit d48f9e5
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,15 @@ import { useLocation } from "react-router";
import classNames from "classnames";
import { Menu } from "@headlessui/react";
import { logOut } from "@/pages/Auth/store/actions";
import { FeatureFlags } from "@/shared/constants";
import { useRoutesContext } from "@/shared/contexts";
import { useFeatureFlag } from "@/shared/hooks/useFeatureFlag";
import {
Avatar3Icon,
BillingIcon,
LogoutIcon,
NotificationsIcon,
} from "@/shared/icons";
import ReportIcon from "@/shared/icons/report.icon";
import ThemeIcon from "@/shared/icons/theme.icon";
import { toggleTheme } from "@/shared/store/actions";
import { clearFirestoreCache } from "@/shared/utils/firebase";
import { MenuItem } from "./components";
import { Item, ItemType } from "./types";
import styles from "./MenuItems.module.scss";
Expand Down Expand Up @@ -47,9 +43,6 @@ const MenuItems: FC<MenuItemsProps> = (props) => {
const { pathname } = useLocation();
const isV04 = pathname.includes("-v04");

const featureFlags = useFeatureFlag();
const isHavingAnIssueEnabled = featureFlags?.get(FeatureFlags.HavingAnIssue);

const toggleThemeMenuItem = {
key: "theme",
type: ItemType.Button,
Expand Down Expand Up @@ -93,20 +86,8 @@ const MenuItems: FC<MenuItemsProps> = (props) => {
},
];

if (isHavingAnIssueEnabled) {
menuItems.push({
key: "issue",
text: "Having an issue?",
icon: <ReportIcon />,
type: ItemType.Button,
onClick: () => {
clearFirestoreCache();
},
});
}

return menuItems;
}, [isHavingAnIssueEnabled, isV04, toggleThemeMenuItem]);
}, [isV04, toggleThemeMenuItem]);

return (
<Menu.Items as={React.Fragment}>
Expand Down
98 changes: 1 addition & 97 deletions src/shared/utils/firebase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,109 +9,12 @@ import { local } from "@/config";
import { Environment, REACT_APP_ENV } from "@/shared/constants";
import config from "../../config";

const CACHE_SIZE_LIMIT = 104857600; // 100 MB

interface FirebaseError extends Error {
code: string;
}

const app = firebase.initializeApp(config.firebase);

let db: firebase.firestore.Firestore;

// Function to enable Firestore persistence and apply settings
function enableUnlimitedCachePersistence(): Promise<void> {
db = firebase.firestore(); // Initialize Firestore instance here

const settings = {
cacheSizeBytes: CACHE_SIZE_LIMIT,
};

db.settings(settings); // Apply settings before any Firestore operation

return db
.enablePersistence({ synchronizeTabs: true }) // Enable persistence
.then(() => {
console.log("Persistence enabled successfully.");
return;
})
.catch(handlePersistenceError); // Handle errors
}

// Function to handle Firestore persistence errors
function handlePersistenceError(err: any) {
console.error("Persistence error:", err); // Log the error

if (err.code === "failed-precondition") {
console.log("Multiple tabs open or other conflict.");
} else if (err.code === "unimplemented") {
console.log("Persistence is not supported in this browser.");
} else if (
err.name === "QuotaExceededError" ||
err.code === "QuotaExceededError"
) {
console.log("Storage quota exceeded. Consider clearing cache.");
clearFirestoreCache(); // Clear cache and try reinitialization
} else {
console.error("Error enabling persistence:", err);
reinitializeFirestoreWithPersistence(); // Reinitialize Firestore with persistence
}
}

// Function to reinitialize Firestore with persistence
function reinitializeFirestoreWithPersistence() {
db.terminate() // Terminate the Firestore instance first
.then(() => db.clearPersistence()) // Clear persistence
.then(() => {
db = firebase.firestore(); // Reinitialize Firestore
const settings = { cacheSizeBytes: CACHE_SIZE_LIMIT };
db.settings(settings); // Apply settings again
return db.enablePersistence({ synchronizeTabs: true });
})
.then(() => {
console.log("Persistence re-enabled.");
return;
})
.catch(handlePersistenceError); // Handle any errors during reinitialization
}

// Function to clear Firestore cache and re-enable persistence
export function clearFirestoreCache() {
db.terminate()
.then(() => {
console.log("Firestore instance terminated.");
return db.clearPersistence(); // Safe to clear persistence now
})
.then(() => {
console.log("Persistence cleared. Waiting before reinitializing...");
return new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 2 seconds
})
.then(() => {
console.log("Cache cleared successfully.");
reinitializeFirestoreWithPersistence(); // Reinitialize Firestore
window.location.reload(); // Reload page to apply changes
return;
})
.catch((err) => {
if (err.code === "failed-precondition") {
console.log("Cannot clear persistence: Firestore is still running.");
} else {
console.error("Error clearing persistence cache:", err);
}
});
}

// Call this function in your entry point (before using Firestore elsewhere)
enableUnlimitedCachePersistence()
.then(() => {
console.log("Firestore persistence setup complete.");
// You can now safely access Firestore (db) or perform any Firestore operations
return;
})
.catch(() => {
console.log("Firestore persistence setup error.");
});

// Enable persistence in the local environment (with Firestore and Auth emulators)
if (REACT_APP_ENV === Environment.Local) {
firebase.auth().useEmulator(local.firebase.authDomain);
Expand All @@ -136,6 +39,7 @@ if (typeof window !== "undefined" && typeof window.fetch !== "undefined") {
}

export { perf };
// firebase.firestore.setLogLevel("debug");

export const isFirebaseError = (error: any): error is FirebaseError =>
(error && error.code && error.code.startsWith("auth/")) ||
Expand Down

0 comments on commit d48f9e5

Please sign in to comment.