forked from plumatic/fnhouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guestbook.clj
71 lines (63 loc) · 2.09 KB
/
guestbook.clj
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
(ns guesthouse.guestbook
"A set of handlers for adding, viewing, searching for,
and deleting guestbook entries"
(:use plumbing.core)
(:require
[schema.core :as s]
[clojure.string :as str]
[guesthouse.schemas :as schemas]))
(set! *warn-on-reflection* true)
(defnk $entries$POST
"Add a new entry to the guestbook"
{:responses {200 schemas/ClientEntry}}
[[:request body :- schemas/EntryData]
[:resources guestbook index]]
(let [entry-id (swap! index inc)
indexed-entry (assoc body :index entry-id)]
(swap! guestbook assoc entry-id indexed-entry)
{:body indexed-entry}))
(defnk $entries$GET
"View the current entries in the guestbook"
{:responses {200 [schemas/ClientEntry]}}
[[:resources guestbook]]
{:body (vals @guestbook)})
(defnk $search$GET
"Find enties by name"
{:responses {200 [schemas/ClientEntry]}}
[[:request [:query-params q :- String]]
[:resources guestbook]]
{:body
(filter
(fnk [name :- String]
(.contains (str/lower-case name) (str/lower-case q)))
(vals @guestbook))})
(defnk $entries$:entry-id$GET
"Get the entry at the given id"
{:responses {200 schemas/ClientEntry}}
[[:request [:uri-args entry-id :- Long]]
[:resources guestbook]]
{:body (safe-get @guestbook entry-id)})
(defnk $entries$:entry-id$POST
"Update the entry at the given id"
{:responses {200 schemas/Ack
404 schemas/Missing}}
[[:request
[:uri-args entry-id :- Long]
body :- schemas/EntryData]
[:resources guestbook]]
(if-not (get @guestbook entry-id)
(schemas/not-found (format "Entry %s not found" entry-id))
(do (swap! guestbook assoc entry-id (assoc body :index entry-id))
schemas/ack)))
(defnk $entries$:entry-id$DELETE
"Delete the entry at the given id"
{:responses {200 schemas/Ack
404 schemas/Missing}}
[[:request
[:uri-args entry-id :- Long]]
[:resources guestbook]]
(let [[old new] (swap-pair! guestbook dissoc entry-id)]
(if-not (get old entry-id)
(schemas/not-found (format "Entry %s not found" entry-id))
schemas/ack)))
(set! *warn-on-reflection* false)