Back

Version 71

2/21/2024
/** @jsxImportSource https://esm.sh/react */
import { renderToString } from "https://esm.sh/react-dom@18.2.0/server";
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { html } from "https://esm.town/v/stevekrouse/html";
import todo_setup_table from "https://esm.town/v/stevekrouse/todo_setup_table";
import { TodoApp } from "https://esm.town/v/stevekrouse/TodoApp";
import { zip } from "npm:lodash-es";

todo_setup_table();

async function addTodo(req: Request) {
const name = await req.json();
await sqlite.execute({ sql: `insert into todos(text) values (?)`, args: [name] });
}

async function getTodos() {
let { columns, rows } = await sqlite.execute(`select * from todos`);
return rows.map(row => Object.fromEntries(zip(columns, row)));
}

export let todo_list = async (req: Request): Promise<Response> => {
let url = new URL(req.url);
if (url.pathname === "/todos" && req.method === "GET")
return Response.json(await getTodos());
if (url.pathname === "/todos" && req.method === "POST") {
await addTodo(req);
return Response.json(await getTodos());
}

let intiialTodos = await getTodos();
return html(renderToString(<TodoApp initialTodos={intiialTodos} />));
};
stevekrouse-todo_list.web.val.run
Updated: February 22, 2024