import { serve } from "https://deno.land/std@0.168.0/http/server.ts"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2.38.4"; const supabaseUrl = Deno.env.get("SUPABASE_URL")!; const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!; serve(async (req) => { try { const supabase = createClient(supabaseUrl, supabaseKey); // 删除3个月未访问的集合 const threeMonthsAgo = new Date(); threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); const { data: expiredCollections, error: fetchError } = await supabase .from("stock_collections") .select("id") .lt("last_accessed_at", threeMonthsAgo.toISOString()); if (fetchError) { throw new Error(`查询过期集合失败: ${fetchError.message}`); } if (!expiredCollections || expiredCollections.length === 0) { return new Response( JSON.stringify({ message: "没有过期的集合需要清理" }), { headers: { "Content-Type": "application/json" }, status: 200, } ); } // 删除过期的集合(级联删除关联的股票和分享链接) const collectionIds = expiredCollections.map((c) => c.id); const { error: deleteError } = await supabase .from("stock_collections") .delete() .in("id", collectionIds); if (deleteError) { throw new Error(`删除过期集合失败: ${deleteError.message}`); } return new Response( JSON.stringify({ message: `成功清理 ${expiredCollections.length} 个过期集合`, deletedCount: expiredCollections.length, }), { headers: { "Content-Type": "application/json" }, status: 200, } ); } catch (error: unknown) { const errorMessage = error instanceof Error ? error.message : String(error); return new Response( JSON.stringify({ error: errorMessage }), { headers: { "Content-Type": "application/json" }, status: 500, } ); } });