-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.carp
64 lines (53 loc) · 2.16 KB
/
main.carp
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
(Project.config "title" "koi-notes-example")
(load "https://github.com/TimDeve/hoquet@v0.1.1")
(load "https://github.com/carpentry-org/sqlite3@0.0.5")
(load "../../koi.carp")
(load "models.carp")
(load "repository.carp")
(use Koi)
(defn home-html-template []
(with Elements
(html {}
[(head {}
[(meta {@"charset" @"UTF-8"})
(link {@"href" @"/static/index.css" @"rel" @"stylesheet"})
(script {@"src" @"/static/index.js" @"async" @"true" @"type" @"module"} [@""])])
(body {}
[(div {@"class" @"container"}
[(h1 {} [@"Notes"])
(div {@"id" @"root"} [])])])])))
(sig get-home-handler (Fn [Req] Res))
(defn get-home-handler [req]
(Res.send (HttpStatus.Ok)
@"text/html"
(home-html-template)))
(sig add-note-handler (Fn [Req] Res))
(defn add-note-handler [req]
(match (Req.json-into NewNote &req)
(Result.Error _) (bad-request)
(Result.Success note)
(match (Repository.add-note note)
(Result.Error err) (do (Clog.error &err)
(Res.send (HttpStatus.InternalServerError)
@"text/plain"
@"500"))
(Result.Success _) (Res.send (HttpStatus.Created)
@"text/plain"
@"201"))))
(sig get-notes-handler (Fn [Req] Res))
(defn get-notes-handler [req]
(match (Repository.get-notes)
(Result.Error err) (do (Clog.error &err)
(Res.send (HttpStatus.InternalServerError)
@"text/plain"
@"500"))
(Result.Success res) (Res.send (HttpStatus.Created)
@"application/json"
(SheriffJSON.marshall (Array Note) &res))))
(defn routes []
[(Route.init (HttpVerb.GET) @"/" get-home-handler)
(Route.init (HttpVerb.GET) @"/api/notes" get-notes-handler)
(Route.init (HttpVerb.POST) @"/api/notes" add-note-handler)])
(defn-do main []
(Repository.create-table)
(serve "localhost" 8080 (Array.concat &[(routes) (static "static")])))