Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend Database Action for Deleting Photos #246

Merged
merged 3 commits into from
Dec 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 94 additions & 2 deletions web/db/actions/caregiver/Photo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import {
deleteObject,
getDownloadURL,
ref,
uploadBytes,
} from "firebase/storage";
import { db, storage } from "../../firebase"; // import firebase storage
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
import { doc, setDoc, Timestamp } from "firebase/firestore";
import { deleteDoc, doc, getDoc, setDoc, Timestamp } from "firebase/firestore";

interface Props {
file: File;
Expand Down Expand Up @@ -59,3 +64,90 @@ export async function uploadPhoto({
return { success: false, error: `Upload failed: ${error}` };
}
}

// TODO check if this works when connecting to frontend
export async function deletePhoto(
babyId: string,
docId: string
): Promise<{ success: boolean; error?: string }> {
try {
// Retrieve the Firestore document
const docRef = doc(db, "babies", babyId, "book", docId);
const docSnap = await getDoc(docRef);

if (!docSnap.exists()) {
return {
success: false,
error: `Document with ID ${docId} does not exist.`,
};
}

// Extract the download URL from the Firestore document
const { imageUrl } = docSnap.data();
if (!imageUrl) {
return {
success: false,
error: `Document with ID ${docId} does not contain an imageUrl.`,
};
}

// Extract the storage path from the download URL
const storagePath = extractStoragePathFromUrl(imageUrl);
if (!storagePath) {
return {
success: false,
error: "Failed to extract storage path from imageUrl.",
};
}

// Delete the file from Firebase Storage
const storageRef = ref(storage, storagePath);
await deleteObject(storageRef);

// Delete the Firestore document
await deleteDoc(docRef);

return { success: true };
} catch (error: any) {
console.error("Error deleting photo:", error);
return { success: false, error: `Delete failed: ${error.message}` };
}
}

function extractStoragePathFromUrl(downloadURL: string): string | null {
try {
const url = new URL(downloadURL); // Use URL parsing
const path = url.pathname.split("/o/")[1]; // Split at `/o/` to get the encoded path
return path ? decodeURIComponent(path) : null; // Decode the path
} catch (error) {
console.error("Error extracting storage path from URL:", error);
return null;
}
}

export async function deletePhotos(
photoEntries: { babyId: string; docId: string }[]
): Promise<{
success: boolean;
results: { docId: string; success: boolean; error?: string }[];
}> {
const results = [];

for (const { babyId, docId } of photoEntries) {
try {
const response = await deletePhoto(babyId, docId);
results.push({ docId, success: response.success, error: response.error });
} catch (error: any) {
results.push({
docId,
success: false,
error: `Error deleting photo with ID ${docId}: ${error.message}`,
});
}
}

// Check overall success (true if all deletions succeed)
const success = results.every((result) => result.success);

return { success, results };
}