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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* This request collector val saves information about incoming requests
* and displays summary statistics on the home page. It uses SQLite for
* persistence and server-side React for rendering the UI. Users can click
* on a request ID to view full details of that request.
*/
/** @jsxImportSource https://esm.sh/react */
import React from "https://esm.sh/react";
import { renderToString } from "https://esm.sh/react-dom/server";
interface RequestData {
id: number;
method: string;
url: string;
headers: string;
ip: string;
timestamp: string;
}
interface Stats {
totalRequests: number;
uniqueIPs: number;
mostCommonMethod: string;
mostCommonPath: string;
}
function App({ requests, stats, fullRequest }: { requests: RequestData[], stats: Stats, fullRequest?: RequestData }) {
return (
<div>
<h1>Request Collector</h1>
{fullRequest ? (
<div>
<h2>Request Details</h2>
<table>
<tbody>
<tr><th>ID</th><td>{fullRequest.id}</td></tr>
<tr><th>Method</th><td>{fullRequest.method}</td></tr>
<tr><th>URL</th><td>{fullRequest.url}</td></tr>
<tr><th>IP</th><td>{fullRequest.ip}</td></tr>
<tr><th>Timestamp</th><td>{fullRequest.timestamp}</td></tr>
<tr><th>Headers</th><td><pre>{fullRequest.headers}</pre></td></tr>
</tbody>
</table>
<p><a href="/">Back to summary</a></p>
</div>
) : (
<>
<h2>Summary Statistics</h2>
<ul>
<li>Total Requests: {stats.totalRequests}</li>
<li>Unique IPs: {stats.uniqueIPs}</li>
<li>Most Common Method: {stats.mostCommonMethod}</li>
<li>Most Common Path: {stats.mostCommonPath}</li>
</ul>
<h2>Recent Requests</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Method</th>
<th>URL</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
{requests.map((req) => (
<tr key={req.id}>
<td><a href={`/?id=${req.id}`}>{req.id}</a></td>
<td>{req.method}</td>
<td>{req.url}</td>
<td>{req.timestamp}</td>
</tr>
))}
</tbody>
</table>
</>
)}
<p>
<a href={import.meta.url.replace("esm.town", "val.town")}>View Source</a>
</p>
</div>
);
}
export default async function server(request: Request): Promise<Response> {
const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
const SCHEMA_VERSION = 1;
const KEY = new URL(import.meta.url).pathname.split("/").at(-1);
// Create table if not exists
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS ${KEY}_requests_${SCHEMA_VERSION} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
method TEXT,
url TEXT,
headers TEXT,
ip TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)