all repos — momix @ main

A CLI tool to manage recipes for Thermomix

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(
57      `/?msg=${encodeURIComponent("La recette a bien été ajoutée")}`
58    );
59  } catch (error) {
60    console.error(error);
61    return c.redirect(
62      `/?error=${encodeURIComponent("Problème lors de l'ajout")}`
63    );
64  }
65});
66
67app.post("/add-grocery-list", async (c) => {
68  const body = await c.req.formData();
69  const enabledRecipeIds = [...body.entries()]
70    .filter(([_, value]) => value === "on")
71    .map(([key]) => key);
72  return c.redirect(`/grocery?recipeIds=${enabledRecipeIds.join(",")}`);
73});
74
75export default app;