-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp-proxy.ts
85 lines (74 loc) · 1.92 KB
/
http-proxy.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { serve } from "bun";
import { Client } from "pg";
const client = new Client({
host: process.env.PROXY_HOST,
user: process.env.PROXY_USER,
database: process.env.PROXY_NAME,
password: process.env.PROXY_PASS,
port: Number(process.env.PROXY_PORT),
});
await client.connect();
const port = Number(process.env.PROXY_HTTP_PORT);
console.log(`Proxy listening on port ${port}`);
serve({
port,
async fetch(req) {
const url = new URL(req.url);
const path = url.pathname;
switch (path) {
case "/query":
return query(req);
case "/status":
return status();
default:
return new Response("Not found", { status: 404 });
}
},
});
/**
* Executes SQL query on indexer database
*/
async function query(req: Request) {
const { sql, params, method } = await req.json();
const sqlBody = sql.replace(/;/g, "");
try {
if (method === "all") {
const result = await client.query({
text: sqlBody,
values: params,
rowMode: "array",
});
return Response.json(result.rows);
}
if (method === "execute") {
const result = await client.query({
text: sqlBody,
values: params,
});
return Response.json(result.rows);
}
return Response.json({ error: "Unknown method value" }, { status: 500 });
} catch (e) {
console.error(e);
return Response.json({ error: "error" }, { status: 500 });
}
}
/**
* Returns status of indexer processor
*/
async function status() {
const result = await client.query("select * from squid_processor.status");
if (result.rows.length > 0) {
const row = result.rows[0];
return Response.json(
{ height: row.height },
{
status: 200,
headers: {
"Cache-Control": `public, max-age=${process.env.PROXY_CACHE_MAX_AGE}, stale-while-revalidate=30`,
},
}
);
}
return Response.json({ height: 0 }, { status: 200 });
}