与 Supabase 存储整合
Edge Functions 可以无缝配合 Supabase Storage 使用。这让你能够:
🌐 Edge Functions work seamlessly with Supabase Storage. This allows you to:
- 直接上传你职能生成的内容
- 为了更好的性能,优先使用缓存模式
- 使用内置 CDN 功能提供文件
基础文件操作 #
🌐 Basic file operations
使用 Supabase 客户端可以直接从你的 Edge Functions 上传文件。你将需要服务器端存储操作的密钥:
🌐 Use the Supabase client to upload files directly from your Edge Functions. You'll need the secret key for server-side storage operations:
import { createClient } from 'npm:@supabase/supabase-js@2'const SUPABASE_SECRET_KEYS = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS')!)Deno.serve(async (req) => { const supabaseAdmin = createClient( Deno.env.get('SUPABASE_URL')!, // If you want to use a different api key, change 'default' to your preferred key name SUPABASE_SECRET_KEYS['default'] ) // Generate your content const fileContent = await generateImage() // Upload to storage const { data, error } = await supabaseAdmin.storage .from('images') .upload(`generated/${filename}.png`, fileContent.body!, { contentType: 'image/png', cacheControl: '3600', upsert: false, }) if (error) { throw error } return new Response(JSON.stringify({ path: data.path }))})在服务器端操作时总是使用 SUPABASE_SECRET_KEYS 之一。切勿在客户端代码中暴露这个密钥!
🌐 Always use one of the SUPABASE_SECRET_KEYS for server-side operations. Never expose this key in client-side code!
优先缓存模式 #
🌐 Cache-first pattern
在生成新内容前检查存储,以提高性能:
🌐 Check storage before generating new content to improve performance:
const STORAGE_URL = 'https://your-project.supabase.co/storage/v1/object/public/images'Deno.serve(async (req) => { const url = new URL(req.url) const username = url.searchParams.get('username') try { // Try to get existing file from storage first const storageResponse = await fetch(`${STORAGE_URL}/avatars/${username}.png`) if (storageResponse.ok) { // File exists in storage, return it directly return storageResponse } // File doesn't exist, generate it const generatedImage = await generateAvatar(username) // Upload to storage for future requests const { error } = await supabaseAdmin.storage .from('images') .upload(`avatars/${username}.png`, generatedImage.body!, { contentType: 'image/png', cacheControl: '86400', // Cache for 24 hours }) if (error) { console.error('Upload failed:', error) } return generatedImage } catch (error) { return new Response('Error processing request', { status: 500 }) }})