stevekrouse-plants.web.val.run
Readme

Made with val writer

With prompt

The app is just a simple plant watering app. 
Had a bunch of plants with different watering schedules. 
I want to be able to add new plants. 
I want to open the app and mark a plant as watered. 
I want to track all watering events. 
Store only a `waterings` table where the plant name is a string.
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
/** @jsxImportSource npm:hono@3/jsx */
import { sqlite } from "https://esm.town/v/std/sqlite?v=5";
import { Hono } from "npm:hono@3";
import humanizeDuration from "npm:humanize-duration";
// Initialize the SQLite database and create the waterings table
sqlite.execute(`
CREATE TABLE IF NOT EXISTS waterings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plant_name TEXT,
watered_on DATETIME
)
`);
const app = new Hono();
// Route to display the main page with list of plants and their last watered date
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}>
{/* compute how long ago it was last watered */}
{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>,
);
});
// Route to handle addition of new plants (adds a record in waterings table)
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("/");
});
// Route to handle marking a plant as watered
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;
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 18, 2024