index.ts 4.09 KB
Newer Older
duanjinfei's avatar
duanjinfei committed
1 2 3 4 5 6 7 8
// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.

// Setup type definitions for built-in Supabase Runtime APIs
import "jsr:@supabase/functions-js/edge-runtime.d.ts"
import { createClient } from 'jsr:@supabase/supabase-js@2'

duanjinfei's avatar
duanjinfei committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// 分页查询函数
async function fetchAllData(supabase, table: string, pageSize: number = 1000) {
  let allData: any[] = [];
  let offset = 0;

  while (true) {
    const { data, error } = await supabase
      .from(table)
      .select('*') // 可以根据需要调整字段
      .order('created_at', { ascending: true }) // 按照创建时间排序
      .range(offset, offset + pageSize - 1); // 分页范围

    if (error) {
      console.error(`Error fetching data from ${table}:`, error);
      throw error;
    }

    if (data && data.length > 0) {
      allData = allData.concat(data); // 合并当前页数据
      offset += pageSize; // 移动到下一页
    } else {
      break; // 如果没有更多数据,则退出循环
    }
  }

  return allData;
}

duanjinfei's avatar
duanjinfei committed
37
Deno.serve(async (req) => {
duanjinfei's avatar
duanjinfei committed
38 39 40
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }
duanjinfei's avatar
duanjinfei committed
41 42 43 44 45 46 47 48 49
  try {
    // const { name } = await req.json()
    const supabase = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
      { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
    )

    // 获取所有 app 数据
duanjinfei's avatar
duanjinfei committed
50
    const allApps = await fetchAllData(supabase, 'app');
duanjinfei's avatar
duanjinfei committed
51 52 53 54 55 56
    // 获取当前时间的整点时间戳
    const timestamp = Math.floor(Date.now() / 3600000) * 3600;

    // 上传所有 app 数据到 storage
    const allAppsJson = JSON.stringify(allApps);
    const allAppsFileName = `app_all_${timestamp}.json`;
duanjinfei's avatar
duanjinfei committed
57
    const bucketName = 'cache'; // 替换为存储桶名称
duanjinfei's avatar
duanjinfei committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

    const { error: allAppsUploadError } = await supabase.storage
      .from(bucketName)
      .upload(allAppsFileName, new Blob([allAppsJson]), {
        contentType: 'application/json',
        upsert: true,
      });

    if (allAppsUploadError) {
      console.error('Error uploading all apps JSON:', allAppsUploadError);
      return new Response(
        JSON.stringify({ error: 'Failed to upload all apps JSON' }),
        { status: 500 }
      );
    }

    // 按 category_id 分组
    const groupedData: Record<string, any[]> = {};
    allApps.forEach((app) => {
      if (!groupedData[app.category_id]) {
        groupedData[app.category_id] = [];
      }
      groupedData[app.category_id].push(app);
    });

    // 上传每个 category_id 的数据
    for (const [categoryId, apps] of Object.entries(groupedData)) {
      const categoryJson = JSON.stringify(apps);
      const categoryFileName = `app_category_${categoryId}_${timestamp}.json`;

      const { error: categoryUploadError } = await supabase.storage
        .from(bucketName)
        .upload(categoryFileName, new Blob([categoryJson]), {
          contentType: 'application/json',
          upsert: true,
        });

      if (categoryUploadError) {
        console.error(
          `Error uploading category ${categoryId} JSON:`,
          categoryUploadError
        );
        return new Response(
          JSON.stringify({
            error: `Failed to upload category ${categoryId} JSON`,
          }),
          { status: 500 }
        );
      }
    }
    return new Response(
      JSON.stringify({
        message: 'All data uploaded successfully',
duanjinfei's avatar
duanjinfei committed
111
        fileName: allAppsFileName,
duanjinfei's avatar
duanjinfei committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
      }),
      { status: 200 }
    );
  } catch (err) {
    console.error('Unexpected error:', err);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
    });
  }
})




/* To invoke locally:

  1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
  2. Make an HTTP request:

  curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/hello-world' \
    --header 'Authorization: Bearer ' \
    --header 'Content-Type: application/json' \
    --data '{"name":"Functions"}'

*/