Xavier Portilla Edo
2025-06-04 13:29:39 +00:00
parent 00633b6a65
commit 4763dc3d53
+41 -6
View File
@@ -1,3 +1,4 @@
import { import {
collection, collection,
addDoc, addDoc,
@@ -26,18 +27,52 @@ export const addCardToCollection = async (
userId: string, userId: string,
cardData: Omit<PokemonCard, 'id' | 'userId' | 'createdAt' | 'updatedAt'> cardData: Omit<PokemonCard, 'id' | 'userId' | 'createdAt' | 'updatedAt'>
): Promise<string> => { ): Promise<string> => {
if (!userId) throw new Error('User ID is required to add a card.'); if (!userId) {
console.error("addCardToCollection: User ID is missing.");
throw new Error('User ID is required to add a card.');
}
try { try {
const docRef = await addDoc(getPokemonCardsCollectionRef(userId), { const collectionRef = getPokemonCardsCollectionRef(userId);
const docPayload = {
...cardData, ...cardData,
userId, // Ensure userId is part of the document data as well for easier querying if needed userId,
createdAt: serverTimestamp(), createdAt: serverTimestamp(),
updatedAt: serverTimestamp(), updatedAt: serverTimestamp(),
}); };
// Log information for debugging, excluding potentially very large imageDataUrl from general log
const payloadKeys = Object.keys(docPayload);
const imageDataUrlLength = docPayload.imageDataUrl ? docPayload.imageDataUrl.length : 0;
console.log(
"Attempting to add card to Firestore. Path:",
collectionRef.path,
"Payload keys:",
payloadKeys.join(', '),
"imageDataUrl length:",
imageDataUrlLength
);
if (imageDataUrlLength > 500 * 1024) { // Warn if image data is > 500KB
console.warn(
`imageDataUrl is very large (length: ${imageDataUrlLength} bytes). This might approach or exceed Firestore's 1MiB document size limit and could cause write failures. Consider storing images in Firebase Storage instead.`
);
}
const docRef = await addDoc(collectionRef, docPayload);
return docRef.id; return docRef.id;
} catch (error) { } catch (error) {
console.error('Error adding card to Firestore: ', error); console.error('Error adding card to Firestore (full error object):', error); // Log the full error object
throw new Error('Failed to add card to collection.'); let detailedMessage = 'Failed to add card to collection.';
if (error instanceof Error) {
detailedMessage = error.message; // Start with the basic error message
// Attempt to access Firebase-specific error code
// Firebase errors often have a 'code' property, but to be safe with typing, we check its existence.
const firebaseError = error as any;
if (firebaseError.code) {
detailedMessage = `Error: ${firebaseError.code} - ${error.message}`;
}
}
throw new Error(detailedMessage); // Throw a new error with the potentially more detailed message
} }
}; };