From ca92e6adf431f2c5bdaf1a463bf09f590b1e38bd Mon Sep 17 00:00:00 2001 From: prachishelke1312 Date: Mon, 8 Jun 2026 22:40:19 +0530 Subject: [PATCH] fix: add orphan image cleanup function --- .../functions/cleanup-orphan-images/README.md | 6 +++ .../functions/cleanup-orphan-images/index.ts | 46 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 backend/supabase/functions/cleanup-orphan-images/README.md create mode 100644 backend/supabase/functions/cleanup-orphan-images/index.ts diff --git a/backend/supabase/functions/cleanup-orphan-images/README.md b/backend/supabase/functions/cleanup-orphan-images/README.md new file mode 100644 index 0000000..9960fd6 --- /dev/null +++ b/backend/supabase/functions/cleanup-orphan-images/README.md @@ -0,0 +1,6 @@ +# Cleanup Orphan Images + +Deletes images from scan-images bucket if: + +- older than 24 hours +- no matching record exists in scans table \ No newline at end of file diff --git a/backend/supabase/functions/cleanup-orphan-images/index.ts b/backend/supabase/functions/cleanup-orphan-images/index.ts new file mode 100644 index 0000000..f15a0ed --- /dev/null +++ b/backend/supabase/functions/cleanup-orphan-images/index.ts @@ -0,0 +1,46 @@ +import { createClient } from "@supabase/supabase-js"; + +const supabase = createClient( + Deno.env.get("SUPABASE_URL")!, + Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")! +); + +Deno.serve(async () => { + const bucket = "scan-images"; + + const { data: files, error } = await supabase.storage + .from(bucket) + .list("", { limit: 1000 }); + + if (error) { + return new Response(error.message, { status: 500 }); + } + + const now = Date.now(); + + for (const file of files ?? []) { + if (!file.created_at) continue; + + const ageHours = + (now - new Date(file.created_at).getTime()) / + (1000 * 60 * 60); + + if (ageHours < 24) continue; + + const { data: scan } = await supabase + .from("scans") + .select("id") + .contains("photo_urls", [file.name]) + .maybeSingle(); + + if (!scan) { + await supabase.storage + .from(bucket) + .remove([file.name]); + + console.log(`Deleted orphan image: ${file.name}`); + } + } + + return new Response("Cleanup completed"); +}); \ No newline at end of file