-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
63 lines (54 loc) · 1.47 KB
/
main.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
// main.ts: Smallweb Starter
// ================================================
// A minimal API template with:
// - Structured logging via Loki
// - Basic rate limiting (60 req/min)
// - Error handling & Supabase integration
// ================================================
import { Hono } from "jsr:@hono/hono";
import { log, LogLevel } from "./log.ts";
import { getLatestScraps } from "./supabase.ts";
import {
getRequestContext,
checkRateLimit,
setCommonHeaders,
getRateLimitResponse,
getErrorResponse,
} from "./middleware.ts";
// Create Hono app
const app = new Hono();
// Middleware to handle rate limiting and common headers
app.use("*", async (c, next) => {
const { clientIp } = getRequestContext(c.req.raw);
log(LogLevel.INFO, "Incoming request", {
path: c.req.path,
method: c.req.method,
clientIp,
});
if (!checkRateLimit(clientIp)) {
return getRateLimitResponse(c.res.headers);
}
setCommonHeaders(c.res.headers);
await next();
});
// Routes
app.get("/", (c) => {
return c.json({
message: "Hello, Smallweb!",
endpoints: ["/api/scraps"],
});
});
app.get("/api/scraps", async (c) => {
try {
const data = await getLatestScraps();
return c.json({ data });
} catch (error) {
// Convert the error response to Hono response
const errorResp = getErrorResponse(error, c.res.headers);
return c.json(await errorResp.json(), errorResp.status);
}
});
// Export the fetch handler
export default {
fetch: app.fetch,
};