Files
supabase/examples/edge-functions/supabase/functions/restful-tasks/index.ts
T
Chris Chinchilla d8bd6b047c docs: Examples Key changes (#45170)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Documentation**
* Updated examples and guides to use Supabase publishable (client) keys
instead of anon keys for client-side usage across frameworks and
platforms.
* Renamed environment variable examples and .env templates to reflect
publishable key naming.
* Adjusted sample requests and client-init examples to send/use the
publishable key via the apikey header where applicable.
* Updated references from service_role to secret for server-side
credential guidance.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: fadymak <fady@fadymak.com>
2026-05-04 12:58:16 +02:00

130 lines
4.4 KiB
TypeScript

// 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.
import { createClient, SupabaseClient } from 'npm:supabase-js@2'
// New approach (v2.95.0+)
import { corsHeaders } from 'jsr:@supabase/supabase-js@2/cors'
// For older versions, use hardcoded headers:
// const corsHeaders = {
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
// 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
// }
interface Task {
name: string
status: number
}
async function getTask(supabaseClient: SupabaseClient, id: string) {
const { data: task, error } = await supabaseClient.from('tasks').select('*').eq('id', id)
if (error) throw error
return new Response(JSON.stringify({ task }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
})
}
async function getAllTasks(supabaseClient: SupabaseClient) {
const { data: tasks, error } = await supabaseClient.from('tasks').select('*')
if (error) throw error
return new Response(JSON.stringify({ tasks }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
})
}
async function deleteTask(supabaseClient: SupabaseClient, id: string) {
const { error } = await supabaseClient.from('tasks').delete().eq('id', id)
if (error) throw error
return new Response(JSON.stringify({}), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
})
}
async function updateTask(supabaseClient: SupabaseClient, id: string, task: Task) {
const { error } = await supabaseClient.from('tasks').update(task).eq('id', id)
if (error) throw error
return new Response(JSON.stringify({ task }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
})
}
async function createTask(supabaseClient: SupabaseClient, task: Task) {
const { error } = await supabaseClient.from('tasks').insert(task)
if (error) throw error
return new Response(JSON.stringify({ task }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
})
}
Deno.serve(async (req) => {
const { url, method } = req
// This is needed if you're planning to invoke your function from a browser.
if (method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders })
}
try {
const SUPABASE_PUBLISHABLE_KEYS = JSON.parse(Deno.env.get('SUPABASE_PUBLISHABLE_KEYS')!)
// Create a Supabase client with the Auth context of the logged in user.
const supabaseClient = createClient(
// Supabase API URL - env var exported by default.
Deno.env.get('SUPABASE_URL') ?? '',
// Supabase publishable key - env var exported by default.
Deno.env.get(SUPABASE_PUBLISHABLE_KEYS['default']) ?? '',
// Create client with Auth context of the user that called the function.
// This way your row-level-security (RLS) policies are applied.
{
global: {
headers: { Authorization: req.headers.get('Authorization')! },
},
}
)
// For more details on URLPattern, check https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
const taskPattern = new URLPattern({ pathname: '/restful-tasks/:id' })
const matchingPath = taskPattern.exec(url)
const id = matchingPath ? matchingPath.pathname.groups.id : null
let task = null
if (method === 'POST' || method === 'PUT') {
const body = await req.json()
task = body.task
}
// call relevant method based on method and id
switch (true) {
case id && method === 'GET':
return getTask(supabaseClient, id as string)
case id && method === 'PUT':
return updateTask(supabaseClient, id as string, task)
case id && method === 'DELETE':
return deleteTask(supabaseClient, id as string)
case method === 'POST':
return createTask(supabaseClient, task)
case method === 'GET':
return getAllTasks(supabaseClient)
default:
return getAllTasks(supabaseClient)
}
} catch (error) {
console.error(error)
return new Response(JSON.stringify({ error: error.message }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
})
}
})