I am facing an issue with my edge function in TypeScript at Supabase that connects to our Postgres database and runs a query. The problem is that the function is being executed twice, regardless of whether I run it locally in the CLI or deploy it to production. Strangely, console logging indicates that the entire function is running twice as well. However, when I check the browser console, it only shows one call to the function on button click. Any suggestions on how to fix this?
Below is the HTML code:
<html>
<head>
<meta charset="utf-8">
<title>Invoke Supabase Function</title>
</head>
<body>
<button id="invoke-button">Invoke Function</button>
<script language="Javascript">
const apiKey = XXXXX
const functionEndPoint = 'http://localhost:54321/functions/v1/';
const inputData = { name: 'Blah' };
const invokeFunction = () => {
console.log('Called invokeFunction');
fetch(`${functionEndPoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(inputData)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
};
document.getElementById('invoke-button').addEventListener('click', invokeFunction);
</script>
</body>
</html>
And here is the function code:
import * as postgres from 'https://deno.land/x/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d6c9d5d2c1d4c3d5e6d0968897928894">[email protected]</a>/mod.ts'
import { serve } from 'https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffcfbebcfbfa1beb8b8a1bf">[email protected]</a>/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1d2d4d1c0c3c0d2c48ccbd2e1908f92928f90">[email protected]</a>'
import { corsHeaders } from '../_shared/cors.ts'
const databaseUrl = "postgresql://XXXXX"
const pool = new postgres.Pool(databaseUrl, 3, true)
serve(async (_req) => {
try {
// Grab a connection from the pool
const connection = await pool.connect()
try {
// Run a query (its actually a non-deterministic fb function/stored proc)
console.log("inbound startgame request...")
const result = await connection.queryObject`SELECT public."newGame"();`
const rr = result.rows
console.log(rr)
// Encode the result as pretty printed JSON
const body = JSON.stringify(
rr,
(key, value) => (typeof value === 'bigint' ? value.toString() : value),
2
)
// Return the response with the correct content type header
return new Response(
JSON.stringify(rr),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
status: 200,
},
)
} finally {
// Release the connection back into the pool
connection.release()
}
} catch (err) {
console.error(err)
return new Response(String(err?.message ?? err), { status: 500 })
}