From 2d9a5a31676d2886a42e34170706a78d93ce1f18 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Tue, 25 Aug 2026 01:10:35 -0700 Subject: Add authors --- src/controller/routes.phel | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'src/controller') diff --git a/src/controller/routes.phel b/src/controller/routes.phel index 5016bb3..5dd41a3 100644 --- a/src/controller/routes.phel +++ b/src/controller/routes.phel @@ -3,13 +3,18 @@ (:require lezer.module.greet :as g) (:require phel.router :as r) (:require phel.http :as h) - (:require phel.pdo)) + (:require phel.pdo) + (:require phel.string :as str)) (def conn (pdo/connect "sqlite:test.db")) (pdo/exec conn "create table if not exists books (id integer primary key autoincrement, title varchar(255))") +(pdo/exec conn "create table if not exists authors (id integer primary key autoincrement, name varchar(255))") +(pdo/exec conn "create table if not exists authors_books (author_id integer, book_id integer)") (defn index-handler [req] - (let [books (pdo/select conn "select * from books")] + (let [books (for [b :in (pdo/select conn "select * from books")] + {:book b + :authors (pdo/select conn "select * from authors where id in (select author_id from authors_books where book_id = :book_id)" {:book_id (:id b)})})] (h/response-from-map {:status 200 :body (index-html books)}))) @@ -18,7 +23,15 @@ :body (g/greet (str "pong - " (rand)))})) (defn book-create-handler [request] - (let [title (get-in request [:parsed-body "title"])] - (pdo/insert conn :books {:title title})) + (let [title (get-in request [:parsed-body "title"]) + authors (str/split (get-in request [:parsed-body "author"]) #",")] + (pdo/with-transaction conn + (let [book-id (pdo/insert conn :books {:title title})] + (for [a :in authors] + (pdo/insert conn :authors_books {:book_id book-id + :author_id (or (pdo/fetch-column (pdo/query conn "select id from authors where name = :name" {:name a})) + (pdo/insert conn :authors {:name a}))}))))) (h/response-from-map {:status 201 - :body (pdo/select conn "select * from books")})) + :body (list (pdo/select conn "select * from books") + (pdo/select conn "select * from authors") + (pdo/select conn "select * from authors_books"))})) -- cgit v1.3-2-g0d8e