-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsql-crud.ts
More file actions
26 lines (21 loc) · 834 Bytes
/
sql-crud.ts
File metadata and controls
26 lines (21 loc) · 834 Bytes
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
import { schemaCompile, validateJson } from "zigttp:validate";
import { sql, sqlExec, sqlMany } from "zigttp:sql";
schemaCompile("todo.create", JSON.stringify({
type: "object",
required: ["title"],
properties: {
title: { type: "string", minLength: 1, maxLength: 120 },
},
}));
sql("listTodos", "SELECT id, title, done FROM todos ORDER BY id ASC");
sql("createTodo", "INSERT INTO todos (title, done) VALUES (:title, 0)");
function handler(req) {
if (req.method === "GET") {
return Response.json({ items: sqlMany("listTodos") });
}
const parsed = validateJson("todo.create", req.body);
if (!parsed.ok) {
return Response.json({ errors: parsed.errors }, { status: 400 });
}
return Response.json(sqlExec("createTodo", { title: parsed.value.title }), { status: 201 });
}