1+ (ns resultful-crud.book
2+ (:require [schema.core :as s]
3+ [resultful-crud.models.book :refer [Book]]
4+ [toucan.db :as db]
5+ [ring.util.http-response :refer [ok not-found created]]
6+ [compojure.api.sweet :refer [GET POST PUT DELETE]]
7+ [resultful-crud.string-util :as str]))
8+
9+ (defn valid-book-title? [title]
10+ (str/non-blank-with-max-length? 100 title))
11+
12+ (defn valid-year-published? [year]
13+ (<= 2000 year 2018 ))
14+
15+ (s/defschema BookRequestSchema
16+ {:title (s/constrained s/Str valid-book-title?)
17+ :year_published (s/constrained s/Int valid-year-published?)})
18+
19+ (defn id->created [id]
20+ (created (str " /books/" id) {:id id}))
21+
22+ (defn create-book-handler [create-book-req]
23+ (-> (db/insert! Book create-book-req)
24+ :id
25+ id->created))
26+
27+ (defn delete-book-handler [book-id]
28+ (db/delete! Book :id book-id)
29+ (ok ))
30+
31+ (defn get-books-handler []
32+ (ok (db/select Book)))
33+
34+ (defn book->response [book]
35+ (if book
36+ (ok book)
37+ (not-found )))
38+
39+ (defn get-book-handler [book-id]
40+ (-> (Book book-id)
41+ book->response))
42+
43+ (defn update-book-handler [id update-book-req]
44+ (db/update! Book id update-book-req)
45+ (ok ))
46+
47+ (def book-routes
48+ [(POST " /books" []
49+ :body [create-book-req BookRequestSchema]
50+ (create-book-handler create-book-req))
51+ (GET " /books" []
52+ (get-books-handler ))
53+ (GET " /books/:id" []
54+ :path-params [id :- s/Int]
55+ (get-book-handler id))
56+ (PUT " /books/:id" []
57+ :path-params [id :- s/Int]
58+ :body [update-book-req BookRequestSchema]
59+ (update-book-handler id update-book-req))
60+ (DELETE " /books/:id" []
61+ :path-params [id :- s/Int]
62+ (delete-book-handler id))])
0 commit comments