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

try saving with refreshed ids when importing to DB fails

This commit is contained in:
Kushagra Gour
2024-06-25 14:54:45 +05:30
parent e8ad1b1599
commit f80a99f15e
2 changed files with 56 additions and 15 deletions

View File

@@ -1,5 +1,5 @@
import { deferred } from './deferred';
import { log } from './utils';
import { log, refreshItemIds } from './utils';
import {
collection,
deleteField,
@@ -170,21 +170,49 @@ export const itemService = {
} else {
const remoteDb = window.db.getDb();
const batch = writeBatch(remoteDb);
/* eslint-disable guard-for-in */
for (var id in items) {
items[id].createdBy = window.user.uid;
batch.set(doc(remoteDb, `items/${id}`), items[id]);
batch.update(doc(remoteDb, `users/${window.user.uid}`), {
[`items.${id}`]: true
});
// Set these items on our cached user object too
window.user.items = window.user.items || {};
window.user.items[id] = true;
function save(items) {
const batch = writeBatch(remoteDb);
/* eslint-disable guard-for-in */
for (var id in items) {
items[id].createdBy = window.user.uid;
batch.set(doc(remoteDb, `items/${id}`), items[id]);
batch.update(doc(remoteDb, `users/${window.user.uid}`), {
[`items.${id}`]: true
});
}
return batch.commit();
/* eslint-enable guard-for-in */
}
batch.commit().then(d.resolve);
/* eslint-enable guard-for-in */
function onSuccess(items) {
window.user.items = window.user.items || {};
for (var id in items) {
// Set these items on our cached user object too
window.user.items[id] = true;
}
d.resolve();
}
save(items)
.then(() => {
onSuccess(items);
})
.catch(e => {
// The only reason we know for this failing is the same creations were
// imported in other account. And hence they can't again be saved in the
// DB with same ID and different `createdBy`
// So now we save them with different IDs
log('Saving imported items failed. Trying with refreshed IDs now...');
const refreshedItems = refreshItemIds(items);
save(refreshedItems)
.then(() => {
onSuccess(refreshedItems);
})
.catch(e => {
log('Error saving items', e);
alert('Your items could not be saved. Please try again later.');
});
});
}
return d.promise;
},

View File

@@ -672,3 +672,16 @@ export function persistAuthUserLocally(user) {
keys.map(key => (obj[key] = user[key]));
window.localStorage.setItem('user', JSON.stringify(obj));
}
/**
* items is an object of {itemId: item}. This fn changes all the keys to new item IDs
* */
export function refreshItemIds(items) {
const newItems = {};
for (var id in items) {
const newId = generateRandomId();
items[id].id = newId;
newItems[newId] = items[id];
}
return newItems;
}