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
/** @jsxImportSource npm:hono/jsx */
import { sqlite } from "https://esm.town/v/std/sqlite?v=5";
import { Hono } from "npm:hono";
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS food_entries2 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
food TEXT,
calories INTEGER,
date TEXT
);
`);
const app = new Hono();
app.get("/", async (c) => {
const today = new Date().toISOString().slice(0, 10);
const entries = await sqlite.execute(`
SELECT food, calories, date FROM food_entries2 ORDER BY date DESC
`);
const dailyCalories = entries.rows.reduce((acc, { date, calories }) => {
acc[date] = (acc[date] || 0) + calories;
return acc;
}, {});
return c.html(
<html>
<head>
<title>Calorie Tracker</title>
<link rel="stylesheet" href="https://unpkg.com/modern-css-reset/dist/reset.min.css" />
</head>
<body>
<div>
<h1>Calorie Tracker</h1>
<h2>Add New Food Entry</h2>
<form method="POST">
<label>
What did you eat?
<input type="text" name="food" required />
</label>
<label>
Calories:
<input type="number" name="calories" required />
</label>
<button type="submit">Add Entry</button>
</form>
</div>
<div>
<h2>Daily Intake</h2>
{Object.keys(dailyCalories).map(date => (
<div key={date}>
<h3>{date}</h3>
<p>Total Calories: {dailyCalories[date]}</p>
</div>
))}
</div>
<div>
<h2>All Entries</h2>
<ul>
{entries.rows.map(([food, calories, date]) => (
<li key={`${date}-${food}`}>{`${date}: ${food} - ${calories} calories`}</li>
))}
</ul>
</div>
</body>
</html>,
);
});
app.post("/", async (c) => {
const body = await c.req.parseBody();
console.log(body);
const { food, calories } = body;
const date = new Date().toISOString().slice(0, 10);
await sqlite.execute({
sql: "INSERT INTO food_entries2 (food, calories, date) VALUES (?, ?, ?)",
args: [food, calories, date],
});
return c.redirect("/");
});
export default app.fetch;