1
0
mirror of https://github.com/chinchang/web-maker.git synced 2025-07-23 23:11:12 +02:00

make db obj sync and enable offline persistance

This commit is contained in:
Kushagra Gour
2024-05-10 15:07:39 +05:30
parent a9931ab5fb
commit c4efbf2399
4 changed files with 26 additions and 69 deletions

View File

@@ -37,9 +37,6 @@ function getArrayFromQuerySnapshot(querySnapshot) {
(() => { (() => {
const FAUX_DELAY = 1; const FAUX_DELAY = 1;
// var db;
var dbPromise;
var local = { var local = {
get: (obj, cb) => { get: (obj, cb) => {
const retVal = {}; const retVal = {};
@@ -75,46 +72,9 @@ function getArrayFromQuerySnapshot(querySnapshot) {
const dbLocalAlias = chrome && chrome.storage ? chrome.storage.local : local; const dbLocalAlias = chrome && chrome.storage ? chrome.storage.local : local;
const dbSyncAlias = chrome && chrome.storage ? chrome.storage.sync : local; const dbSyncAlias = chrome && chrome.storage ? chrome.storage.sync : local;
async function getDb() { function getDb() {
if (dbPromise) {
return dbPromise;
}
log('Initializing firestore'); log('Initializing firestore');
dbPromise = new Promise((resolve, reject) => { return db;
if (db) {
return resolve(db);
}
const firestoreInstance = db;
return firestoreInstance
.enablePersistence({ experimentalTabSynchronization: true })
.then(function () {
// Initialize Cloud Firestore through firebase
// db = firebase.firestore();
// const settings = {
// timestampsInSnapshots: true
// };
// db.settings(settings);
log('firebase db ready', db);
resolve(db);
})
.catch(function (err) {
reject(err.code);
if (err.code === 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
alert(
"Opening Web Maker web app in multiple tabs isn't supported at present and it seems like you already have it opened in another tab. Please use in one tab."
);
trackEvent('fn', 'multiTabError');
} else if (err.code === 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
});
return dbPromise;
} }
async function getUserLastSeenVersion() { async function getUserLastSeenVersion() {
@@ -145,19 +105,16 @@ function getArrayFromQuerySnapshot(querySnapshot) {
function () {} function () {}
); );
if (window.user) { if (window.user) {
const remoteDb = await getDb(); updateDoc(doc(db, `users/${window.user.uid}`), {
updateDoc(doc(remoteDb, `users/${window.user.uid}`), {
lastSeenVersion: version lastSeenVersion: version
}); });
} }
} }
async function getUser(userId) { async function getUser(userId) {
const remoteDb = await getDb(); return getDoc(doc(db, `users/${userId}`)).then(doc => {
return getDoc(doc(remoteDb, `users/${userId}`)).then(doc => {
if (!doc.exists()) { if (!doc.exists()) {
// return setDoc(doc(remoteDb, `users/${userId}`), {}, { merge: true }); // return setDoc(doc(db, `users/${userId}`), {}, { merge: true });
return {}; return {};
} }
@@ -168,8 +125,7 @@ function getArrayFromQuerySnapshot(querySnapshot) {
} }
async function fetchItem(itemId) { async function fetchItem(itemId) {
const remoteDb = await getDb(); getDoc(doc(db, `items/${itemId}`)).then(doc => {
getDoc(doc(remoteDb, `items/${itemId}`)).then(doc => {
if (!doc.exists) return {}; if (!doc.exists) return {};
const data = doc.data(); const data = doc.data();
return data; return data;
@@ -190,9 +146,8 @@ function getArrayFromQuerySnapshot(querySnapshot) {
} }
async function getPublicItemCount(userId) { async function getPublicItemCount(userId) {
const remoteDb = await getDb();
const q = query( const q = query(
collection(remoteDb, 'items'), collection(db, 'items'),
where('createdBy', '==', userId), where('createdBy', '==', userId),
where('isPublic', '==', true) where('isPublic', '==', true)
); );
@@ -201,9 +156,8 @@ function getArrayFromQuerySnapshot(querySnapshot) {
} }
async function getUserSubscriptionEvents(userId) { async function getUserSubscriptionEvents(userId) {
const remoteDb = await getDb();
const q = query( const q = query(
collection(remoteDb, 'subscriptions'), collection(db, 'subscriptions'),
where('userId', '==', userId) where('userId', '==', userId)
); );
@@ -211,9 +165,7 @@ function getArrayFromQuerySnapshot(querySnapshot) {
} }
async function updateUserSetting(userId, settingName, settingValue) { async function updateUserSetting(userId, settingName, settingValue) {
const remoteDb = await getDb(); return updateDoc(doc(db, `users/${userId}`), {
return updateDoc(doc(remoteDb, `users/${userId}`), {
[`settings.${settingName}`]: settingValue [`settings.${settingName}`]: settingValue
}); });
} }

View File

@@ -48,9 +48,6 @@ chrome.runtime.onInstalled.addListener(function callback(details) {
const OFFSCREEN_DOCUMENT_PATH = '/offscreen.html'; const OFFSCREEN_DOCUMENT_PATH = '/offscreen.html';
// A global promise to avoid concurrency issues
let creatingOffscreenDocument;
// Chrome only allows for a single offscreenDocument. This is a helper function // Chrome only allows for a single offscreenDocument. This is a helper function
// that returns a boolean indicating if a document is already active. // that returns a boolean indicating if a document is already active.
async function hasDocument() { async function hasDocument() {

View File

@@ -1,6 +1,10 @@
import { initializeApp } from 'firebase/app'; import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth'; import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore'; import {
initializeFirestore,
persistentLocalCache,
persistentMultipleTabManager
} from 'firebase/firestore';
import { getStorage } from 'firebase/storage'; import { getStorage } from 'firebase/storage';
const config = { const config = {
@@ -16,5 +20,9 @@ const app = initializeApp(config);
export { app }; export { app };
export const auth = getAuth(app); export const auth = getAuth(app);
export const db = getFirestore(app);
export const storage = getStorage(app); export const storage = getStorage(app);
export const db = initializeFirestore(app, {
localCache: persistentLocalCache({
tabManager: persistentMultipleTabManager()
})
});

View File

@@ -16,7 +16,7 @@ import {
export const itemService = { export const itemService = {
async getItem(id) { async getItem(id) {
var remoteDb = await window.db.getDb(); var remoteDb = window.db.getDb();
return getDoc(doc(remoteDb, `items/${id}`)) return getDoc(doc(remoteDb, `items/${id}`))
.then(doc => { .then(doc => {
return doc.data(); return doc.data();
@@ -52,7 +52,7 @@ export const itemService = {
const items = []; const items = [];
if (window.user && !shouldFetchLocally) { if (window.user && !shouldFetchLocally) {
var remoteDb = await window.db.getDb(); var remoteDb = window.db.getDb();
const q = query( const q = query(
collection(remoteDb, 'items'), collection(remoteDb, 'items'),
@@ -94,7 +94,7 @@ export const itemService = {
}, },
async setUser() { async setUser() {
const remoteDb = await window.db.getDb(); const remoteDb = window.db.getDb();
return setDoc(doc(remoteDb, `users/${window.user.uid}`), { return setDoc(doc(remoteDb, `users/${window.user.uid}`), {
items: {} items: {}
}); });
@@ -123,7 +123,7 @@ export const itemService = {
} }
// LOGGED IN // LOGGED IN
var remoteDb = await window.db.getDb(); var remoteDb = window.db.getDb();
item.createdBy = window.user.uid; item.createdBy = window.user.uid;
setDoc(doc(remoteDb, `items/${id}`), item, { setDoc(doc(remoteDb, `items/${id}`), item, {
merge: true merge: true
@@ -196,7 +196,7 @@ export const itemService = {
window.db.local.remove(id, d.resolve); window.db.local.remove(id, d.resolve);
return d.promise; return d.promise;
} }
const remoteDb = await window.db.getDb(); const remoteDb = window.db.getDb();
log(`Starting to save item ${id}`); log(`Starting to save item ${id}`);
return deleteDoc(doc(remoteDb, `items/${id}`)) return deleteDoc(doc(remoteDb, `items/${id}`))
.then(() => { .then(() => {
@@ -220,7 +220,7 @@ export const itemService = {
} }
); );
} }
const remoteDb = await window.db.getDb(); const remoteDb = window.db.getDb();
return updateDoc(doc(remoteDb, `users/${window.user.uid}`), { return updateDoc(doc(remoteDb, `users/${window.user.uid}`), {
[`items.${itemId}`]: true [`items.${itemId}`]: true
}) })
@@ -247,7 +247,7 @@ export const itemService = {
} }
); );
} }
const remoteDb = await window.db.getDb(); const remoteDb = window.db.getDb();
return updateDoc(doc(remoteDb, `users/${window.user.uid}`), { return updateDoc(doc(remoteDb, `users/${window.user.uid}`), {
[`items.${itemId}`]: deleteField() [`items.${itemId}`]: deleteField()
}) })