index.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * Purge Articles Edge Function
  3. * Version: 2.0
  4. * Last updated: 2025-01-20
  5. * Purpose: Automatically purge old articles and send email reports to admins
  6. */
  7. import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
  8. import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
  9. const corsHeaders = {
  10. 'Access-Control-Allow-Origin': '*',
  11. 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
  12. };
  13. serve(async (req) => {
  14. console.log('🚀 Purge-articles function invoked at', new Date().toISOString());
  15. // Handle CORS preflight requests
  16. if (req.method === 'OPTIONS') {
  17. console.log('📝 CORS preflight request handled');
  18. return new Response(null, { headers: corsHeaders });
  19. }
  20. try {
  21. console.log('🗑️ Starting automatic article purge...');
  22. // Create Supabase client
  23. const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
  24. const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
  25. const supabase = createClient(supabaseUrl, supabaseServiceKey);
  26. // Call the purge function
  27. const { data, error } = await supabase.rpc('purge_old_articles');
  28. if (error) {
  29. console.error('Error calling purge_old_articles:', error);
  30. throw error;
  31. }
  32. console.log('Purge completed successfully:', data);
  33. const result = data[0];
  34. const deletedCount = result.deleted_count;
  35. const adminEmails = result.admin_emails;
  36. console.log(`Deleted ${deletedCount} articles`);
  37. console.log(`Admin emails:`, adminEmails);
  38. // Send email report to admins
  39. if (adminEmails && adminEmails.length > 0) {
  40. console.log('Sending purge report to admins...');
  41. const emailResponse = await supabase.functions.invoke('send-purge-report', {
  42. body: {
  43. deletedCount,
  44. adminEmails,
  45. timestamp: new Date().toISOString()
  46. }
  47. });
  48. if (emailResponse.error) {
  49. console.error('Error sending purge report:', emailResponse.error);
  50. } else {
  51. console.log('Purge report sent successfully');
  52. }
  53. }
  54. return new Response(
  55. JSON.stringify({
  56. success: true,
  57. deletedCount,
  58. reportSent: adminEmails && adminEmails.length > 0
  59. }),
  60. {
  61. status: 200,
  62. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  63. }
  64. );
  65. } catch (error: any) {
  66. console.error('Error in purge-articles function:', error);
  67. return new Response(
  68. JSON.stringify({
  69. success: false,
  70. error: error?.message || 'Unknown error'
  71. }),
  72. {
  73. status: 500,
  74. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  75. }
  76. );
  77. }
  78. });