blob: 5dd41a3e44f4143833dc1f52f8aedc1f2aaaf72f (
plain)
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
27
28
29
30
31
32
33
34
35
36
37
|
(ns lezer.controller.routes
(:require lezer.view.main :refer [index-html])
(:require lezer.module.greet :as g)
(:require phel.router :as r)
(:require phel.http :as h)
(: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 (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)})))
(defn ping-handler [req]
(h/response-from-map {:status 200
:body (g/greet (str "pong - " (rand)))}))
(defn book-create-handler [request]
(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 (list (pdo/select conn "select * from books")
(pdo/select conn "select * from authors")
(pdo/select conn "select * from authors_books"))}))
|