import { sqlite } from "https://esm.town/v/std/sqlite?v=5";
import { Hono } from "npm:hono@3";
import humanizeDuration from "npm:humanize-duration";
sqlite.execute(`
CREATE TABLE IF NOT EXISTS waterings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plant_name TEXT,
watered_on DATETIME
)
`);
const app = new Hono();
app.get("/", async (c) => {
const waterings = await sqlite.execute(`
SELECT plant_name, max(watered_on) as last_watered
FROM waterings
GROUP BY plant_name
ORDER BY plant_name
`);
return c.html(
<html>
<head>
<title>Plant Watering Tracker</title>
<script src="https://esm.town/v/stevekrouse/localtime" />
</head>
<body>
<h1>Plant Watering Tracker</h1>
<form method="POST">
<input type="text" name="plant_name" placeholder="Plant Name" required />
<button type="submit">Add New Plant</button>
</form>
<ul>
{waterings.rows.map(([plant_name, last_watered]) => (
<li key={plant_name}>
{}
{plant_name} - Last watered: <local-time datetime={last_watered} />{" "}
{humanizeDuration(Date.now() - new Date(last_watered).getTime(), { round: true })} ago
<form method="POST" action={`/water/${plant_name}`}>
<button type="submit">Water Now</button>
</form>
</li>
))}
</ul>
</body>
</html>,
);
});
app.post("/", async (c) => {
const form = await c.req.formData();
const plant_name = form.get("plant_name");
await sqlite.execute({
sql: "INSERT INTO waterings (plant_name, watered_on) VALUES (?, ?)",
args: [plant_name, new Date().toISOString()],
});
return c.redirect("/");
});
app.post("/water/:plant_name", async (c) => {
const plant_name = c.req.param("plant_name");
await sqlite.execute({
sql: "INSERT INTO waterings (plant_name, watered_on) VALUES (?, ?)",
args: [plant_name, new Date().toISOString()],
});
return c.redirect("/");
});
export default app.fetch;