/
deno_postgres.ts
49 lines (41 loc) · 1004 Bytes
/
deno_postgres.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
import fastro, { Context, HttpRequest } from "$fastro/mod.ts";
import { Client } from "https://deno.land/x/postgres@v0.17.0/mod.ts";
const client = new Client({
user: "postgres",
database: "postgres",
password: "postgres",
hostname: "localhost",
port: 5432,
});
// init table and data
await createTable();
// init connection
await client.connect();
async function getData() {
const { rows } = await client.queryObject`SELECT * FROM todos WHERE id = 1`;
return rows;
}
const f = new fastro();
f.get(
"/",
async (_req: HttpRequest, ctx: Context) => {
const data = await getData();
return ctx.send(data, 200);
},
);
await f.serve();
async function createTable() {
if (!client) throw new Error();
await client.connect();
try {
await client.queryObject`
CREATE TABLE IF NOT EXISTS todos (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL
)
`;
await client.queryObject`INSERT INTO todos (title) VALUES ('hello')`;
} finally {
await client.end();
}
}