From 186718763551445ab077a3ec7fcd567d2c2e5d94 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Tue, 17 Jun 2025 08:45:09 +0100 Subject: [PATCH] Fix broken reference deletion --- src/lib/server/cloudinary-audit.ts | 27 +++++++++++++++-------- src/routes/admin/media/audit/+page.svelte | 22 ++++++++++++++++-- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/src/lib/server/cloudinary-audit.ts b/src/lib/server/cloudinary-audit.ts index e1e76f5..1c51b60 100644 --- a/src/lib/server/cloudinary-audit.ts +++ b/src/lib/server/cloudinary-audit.ts @@ -247,29 +247,38 @@ export async function cleanupBrokenReferences(publicIds: string[]): Promise<{ }) for (const media of mediaToClean) { - let updated = false - const updates: any = {} + let shouldDelete = false + let updateThumbnail = false + // Check if the main URL is broken if (media.url?.includes('cloudinary.com')) { const publicId = extractPublicId(media.url) if (publicId && publicIds.includes(publicId)) { - updates.url = null - updated = true + // If the main URL is broken, we need to delete the entire record + // since url is a required field + shouldDelete = true } } - if (media.thumbnailUrl?.includes('cloudinary.com')) { + // Check if only the thumbnail is broken + if (!shouldDelete && media.thumbnailUrl?.includes('cloudinary.com')) { const publicId = extractPublicId(media.thumbnailUrl) if (publicId && publicIds.includes(publicId)) { - updates.thumbnailUrl = null - updated = true + updateThumbnail = true } } - if (updated) { + if (shouldDelete) { + // Delete the media record entirely since the main URL is broken + await prisma.media.delete({ + where: { id: media.id } + }) + results.cleanedMedia++ + } else if (updateThumbnail) { + // Only update the thumbnail to null if it's broken await prisma.media.update({ where: { id: media.id }, - data: updates + data: { thumbnailUrl: null } }) results.cleanedMedia++ } diff --git a/src/routes/admin/media/audit/+page.svelte b/src/routes/admin/media/audit/+page.svelte index f54abbc..1e2b2bd 100644 --- a/src/routes/admin/media/audit/+page.svelte +++ b/src/routes/admin/media/audit/+page.svelte @@ -465,8 +465,14 @@

Are you sure you want to clean up {auditData?.missingReferences.length || 0} broken references?

-

⚠️ This will remove Cloudinary URLs from database records where the files no longer exist.

-

This action cannot be undone.

+

⚠️ This will:

+ +

This action cannot be undone.