Merge pull request #12391 from samaybar/master

chore: add postgres-on-the-edge example
This commit is contained in:
Thor 雷神 Schaeff authored and GitHub committed 2023-02-14 11:35:37 +08:00
commit e2c6f585f0
3 files changed
+63

No files matched your search

@@ -0,0 +1,2 @@
#Use PolyScale connection string with application_name parameter to get code-free database caching
DATABASE_URL="postgresql:/DB_USERNAME:DB_PASSWORD@psedge.global:5432/postgres?application_name=POLYSCALE_CACHE_ID"
@@ -0,0 +1,18 @@
# postgres-on-the-edge
This function allows you to access your Supabase database directly via TCP from an edge function.
You can add a global cache to your database for fast access to your data, globally by simply connecting your Supabase database to [PolyScale](https://polyscale.ai).
## Setup
1. Rename `.env.example` to `.env`
2. Insert Supabase database connection string for `DATABASE_URL` in `.env` file
3. (Optional) Create PolyScale cache - see [instructions](https://supabase.com/docs/guides/integrations/polyscale) for adding a PolyScale cache.
4. Replace `DATABASE_URL` with PolyScale connection string.
## Deploy
1. Run `supabase functions deploy --no-verify-jwt postgres-on-the-edge`
2. Run `supabase secrets set --env-file supabase/functions/postgres-on-the-edge/.env`
Learn more about creating this function [here](https://www.youtube.com/watch?v=cl7EuF1-RsY).
@@ -0,0 +1,43 @@
import * as postgres from 'https://deno.land/x/postgres@v0.14.2/mod.ts'
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
// Get the connection string from the environment variable "DATABASE_URL"
const databaseUrl = Deno.env.get('DATABASE_URL')!
// Create a database pool with three connections that are lazily established
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
const result = await connection.queryObject`SELECT * FROM animals`
const animals = result.rows // [{ id: 1, name: "Lion" }, ...]
console.log(animals)
// Encode the result as pretty printed JSON
const body = JSON.stringify(
animals,
(_key, value) => (typeof value === 'bigint' ? value.toString() : value),
2
)
// Return the response with the correct content type header
return new Response(body, {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
})
} finally {
// Release the connection back into the pool
connection.release()
}
} catch (err) {
console.error(err)
return new Response(String(err?.message ?? err), { status: 500 })
}
})