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 const ingredients = getGroceryList(db, recipeIds);
42 return c.html(
43 <Layout url={c.req.url}>
44 <a href="/">Retour</a>
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 await storeRecipe(db, recipeId as string);
56 return c.redirect("/?msg=La recette a bien été ajoutée");
57 } catch (error) {
58 console.error(error);
59 return c.redirect("/?error=Erreur lors de l'ajout de la recette");
60 }
61});
62
63app.post("/add-grocery-list", async (c) => {
64 const body = await c.req.formData();
65 const enabledRecipeIds = [...body.entries()]
66 .filter(([_, value]) => value === "on")
67 .map(([key]) => key);
68 return c.redirect(`/grocery?recipeIds=${enabledRecipeIds.join(",")}`);
69});
70
71export default app;