Files
Sauci/apps/supabase/functions/redeem-code/index.ts
T
jjbruntonandClaude Opus 4.5 6f1be7a4e1 Fix supabase-js Deno compatibility by pinning to v2.45.0
The latest supabase-js@2.92.0 has a Deno compatibility bug with
createRequire that causes all edge functions to fail with:
"The argument 'filename' must be a file URL object..."

Pin all edge functions to @2.45.0 with ?target=deno parameter
to ensure Deno-compatible builds from esm.sh.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 21:55:35 +00:00

74 lines
2.7 KiB
TypeScript

import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0?target=deno";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
interface RedeemCodeBody {
email: string;
code: string;
}
Deno.serve(async (req) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
// Use service role for database operations since this is unauthenticated
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Parse request body
const { email, code }: RedeemCodeBody = await req.json();
if (!email || typeof email !== "string" || email.trim() === "") {
return new Response(
JSON.stringify({ success: false, error: "Please enter your email address" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!code || typeof code !== "string" || code.trim() === "") {
return new Response(
JSON.stringify({ success: false, error: "Please enter a redemption code" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Call the database function to redeem the code
const { data, error } = await supabase.rpc("redeem_code_by_email", {
p_email: email.trim(),
p_code: code.trim(),
});
if (error) {
console.error("RPC error:", error);
return new Response(
JSON.stringify({ success: false, error: "Failed to redeem code. Please try again." }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// The RPC returns a JSONB object with success, error, or message
return new Response(
JSON.stringify(data),
{
status: data.success ? 200 : 400,
headers: { ...corsHeaders, "Content-Type": "application/json" }
}
);
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ success: false, error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});