The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: background tasks updates (#30454)
Thor 雷神 Schaefff7518c28961f
diff --git a/apps/docs/content/guides/functions/background-tasks.mdx b/apps/docs/content/guides/functions/background-tasks.mdxindex 2ad76d7028d..7eb79415be5 100644--- a/apps/docs/content/guides/functions/background-tasks.mdx+++ b/apps/docs/content/guides/functions/background-tasks.mdx@@ -3,6 +3,7 @@ id: 'function-background-tasks'title: 'Background Tasks'description: 'How to run background tasks in an Edge Function outside of the request handler'subtitle: 'How to run background tasks in an Edge Function outside of the request handler'+tocVideo: 'rSKBTJxG9VA'---Edge Function instances can process background tasks outside of the request handler. Background tasks are useful for asynchronous operations like uploading a file to Storage, updating a database, or sending events to a logging service. You can respond to the request immediately and leave the task running in the background.@@ -12,18 +13,18 @@ A background task can run until the Edge Function instance hits its [wall-clockHere's an example of defining a background task using a custom event.```ts-// define a custom event+// Define a custom event type for the background task.class MyBackgroundTaskEvent extends Event {- readonly taskPromise: Promise<string>+ readonly taskPromise: Promise<Response>- constructor(taskPromise) {+ constructor(taskPromise: Promise<Response>) {super('myBackgroundTask')this.taskPromise = taskPromise}}-globalThis.addEventListener('myBackgroundTask', async (event: MyBackgroundTaskEvent) => {- const res = await event.taskPromise+globalThis.addEventListener('myBackgroundTask', async (event) => {+ const res = await (event as MyBackgroundTaskEvent).taskPromiseconsole.log(await res.json())})diff --git a/examples/edge-functions/supabase/functions/background-upload-storage/index.ts b/examples/edge-functions/supabase/functions/background-upload-storage/index.tsnew file mode 100644index 00000000000..6ab56876341--- /dev/null+++ b/examples/edge-functions/supabase/functions/background-upload-storage/index.ts@@ -0,0 +1,76 @@+import { createClient } from 'jsr:@supabase/[email protected]'+import OpenAI from 'https://deno.land/x/[email protected]/mod.ts'++const client = new OpenAI({ apiKey: Deno.env.get('OPENAI_API_KEY')! })++const supabase = createClient(+ Deno.env.get('SUPABASE_URL')!,+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!+)++type StorageFileApi = ReturnType<typeof supabase.storage.from>+type StorageUploadPromise = ReturnType<StorageFileApi['upload']>++class MyBackgroundTaskEvent extends Event {+ readonly taskPromise: StorageUploadPromise++ constructor(taskPromise: StorageUploadPromise) {+ super('myBackgroundTask')+ this.taskPromise = taskPromise+ }+}++globalThis.addEventListener('myBackgroundTask', async (event) => {+ const { data, error } = await (event as MyBackgroundTaskEvent).taskPromise+ console.log({ data, error })+})++Deno.serve(async (req) => {+ const url = new URL(req.url)+ const params = new URLSearchParams(url.search)+ const text = params.get('text')++ if (!text) {+ return new Response(JSON.stringify({ error: 'Text parameter is required' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ })+ }++ try {+ const response = await client.audio.speech.create({+ model: 'tts-1',+ voice: 'nova',+ input: text,+ })++ const stream = response.body+ if (!stream) {+ throw new Error('No stream')+ }++ // Branch stream to Supabase Storage+ const [browserStream, storageStream] = stream.tee()++ // Upload to Supabase Storage+ const storageUploadPromise = supabase.storage+ .from('videos')+ .upload(`audio-stream_${Date.now()}.mp3`, storageStream, {+ contentType: 'audio/mp3',+ })+ const event = new MyBackgroundTaskEvent(storageUploadPromise)+ globalThis.dispatchEvent(event)++ return new Response(browserStream, {+ headers: {+ 'Content-Type': 'audio/mp3',+ },+ })+ } catch (error) {+ console.log('error', { error })+ return new Response(JSON.stringify({ error: error.message }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' },+ })+ }+})