-
Notifications
You must be signed in to change notification settings - Fork 6
/
Api.elm
91 lines (81 loc) · 2.05 KB
/
Api.elm
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
module Generated.Api exposing (..)
import Json.Decode exposing (..)
import Json.Decode.Pipeline exposing (..)
import Json.Encode
import Http
import String
type alias Author =
{ name : String
, yearOfBirth : Int
}
decodeAuthor : Decoder Author
decodeAuthor =
decode Author
|> required "name" string
|> required "yearOfBirth" int
encodeAuthor : Author -> Json.Encode.Value
encodeAuthor x =
Json.Encode.object
[ ( "name", Json.Encode.string x.name )
, ( "yearOfBirth", Json.Encode.int x.yearOfBirth )
]
type alias Book =
{ bookId : Maybe (String)
, title : String
, author : Author
}
decodeBook : Decoder Book
decodeBook =
decode Book
|> required "bookId" (maybe string)
|> required "title" string
|> required "author" decodeAuthor
encodeBook : Book -> Json.Encode.Value
encodeBook x =
Json.Encode.object
[ ( "bookId", (Maybe.withDefault Json.Encode.null << Maybe.map Json.Encode.string) x.bookId )
, ( "title", Json.Encode.string x.title )
, ( "author", encodeAuthor x.author )
]
getBooks : Http.Request (List (Book))
getBooks =
Http.request
{ method =
"GET"
, headers =
[]
, url =
String.join "/"
[ "http://localhost:8000/api"
, "books"
]
, body =
Http.emptyBody
, expect =
Http.expectJson (list decodeBook)
, timeout =
Nothing
, withCredentials =
False
}
postBooks : Book -> Http.Request (Book)
postBooks body =
Http.request
{ method =
"POST"
, headers =
[]
, url =
String.join "/"
[ "http://localhost:8000/api"
, "books"
]
, body =
Http.jsonBody (encodeBook body)
, expect =
Http.expectJson decodeBook
, timeout =
Nothing
, withCredentials =
False
}