-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.ts
55 lines (48 loc) · 1.62 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 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 { Pool } from "https://deno.land/x/[email protected]/mod.ts";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
console.log(`Function "postgres-on-the-edge" up and running!`);
// Create a database pool with one connection.
const pool = new Pool(
{
tls: { caCertificates: [Deno.env.get("DB_SSL_CERT")!] },
database: "postgres",
hostname: "db.bljghubhkofddfrezkhn.supabase.co",
user: "postgres",
port: 5432,
password: Deno.env.get("DB_PASSWORD"),
},
1
);
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" }, ...]
// 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 });
}
});