index.ts 2.4 KB

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