server.tsx (view raw)
1import "@std/dotenv/load";
2import { Hono } from "hono";
3import { getGroceryList, getRecipesList, storeRecipe } from "./services.ts";
4import db from "./db.ts";
5import { Layout } from "./web/tsx/layout.tsx";
6import { AddRecipe, GroceryList, RecipesList } from "./web/tsx/components.tsx";
7import { serveStatic } from "hono/deno";
8import { basicAuth } from "hono/basic-auth";
9
10const httpUser = Deno.env.get("HTTP_USER");
11const httpPass = Deno.env.get("HTTP_PASS");
12
13const app = new Hono();
14
15app.use("/style.css", serveStatic({ path: "./web/static/style.css" }));
16
17if (httpUser && httpPass)
18 app.use(
19 "/*",
20 basicAuth({
21 username: httpUser,
22 password: httpPass,
23 })
24 );
25
26app.get("/", (c) => {
27 const recipes = getRecipesList(db);
28 return c.html(
29 <Layout url={c.req.url}>
30 <AddRecipe />
31 <RecipesList recipes={recipes} />
32 </Layout>
33 );
34});
35
36app.get("/grocery", (c) => {
37 const url = new URL(c.req.url);
38 const recipeIds =
39 url.searchParams.get("recipeIds")?.split(",").map(Number) || [];
40 const recipes = getRecipesList(db, recipeIds);
41 console.log({ recipes });
42 const ingredients = getGroceryList(db, recipeIds);
43 return c.html(
44 <Layout url={c.req.url}>
45 <GroceryList recipes={recipes} ingredients={ingredients} />
46 </Layout>
47 );
48});
49
50app.post("/add-recipe", async (c) => {
51 const body = await c.req.formData();
52 const recipeId = body.get("recipeId");
53 if (!recipeId) return c.redirect("/");
54 try {
55 const result = await storeRecipe(db, recipeId as string);
56 console.log(result);
57 return c.redirect("/?msg=Recipe added successfully");
58 } catch (error) {
59 console.error(error);
60 return c.redirect("/?error=An error occured");
61 }
62});
63
64app.post("/add-grocery-list", async (c) => {
65 const body = await c.req.formData();
66 const enabledRecipeIds = [...body.entries()]
67 .filter(([_, value]) => value === "on")
68 .map(([key]) => key);
69 return c.redirect(`/grocery?recipeIds=${enabledRecipeIds.join(",")}`);
70});
71
72export default app;