-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathbreeds.elm
147 lines (107 loc) · 2.52 KB
/
breeds.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as JD exposing (Decoder, map2, field, string, int ,list)
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type Model
= Failure
| Loading
| Success (List Breed)
type alias Breed =
{ id : String
,name: String
,description: String
}
init : () -> (Model, Cmd Msg)
init _ =
(Loading, getbreedList)
api_key = "bdb0f0b8-7f00-4e07-a6e9-e06c10f8bc63"
-- UPDATE
type Msg
= MorePlease
| GotList (Result Http.Error (List Breed))
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
MorePlease ->
(Loading, getbreedList)
GotList result ->
case result of
Ok breedList ->
(Success breedList, Cmd.none)
Err _ ->
(Failure, Cmd.none)
-- handle error message
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h2 [] [ text "Cat breeds" ]
, viewGif model
]
renderImages : Breed -> Html Msg
renderImages lst =
li []
[text lst.name ]
viewGif : Model -> Html Msg
viewGif model =
case model of
Failure ->
div []
[ text "I could not load the cat breeds for some reason. "
]
Loading ->
text "Loading..."
Success breedList ->
div []
[ ul [] (List.map renderImages breedList)]
-- HTTP
getbreedList : Cmd Msg
getbreedList =
let headers = [ Http.header "x-api-key" api_key ]
in
Http.request
{ body = Http.emptyBody
, method="GET"
, url = "https://api.thecatapi.com/v1/breeds"
, expect = Http.expectJson GotList breedListDecoder
, headers = headers
, timeout = Nothing
, tracker = Nothing
}
getbreedCats : String -> Cmd Msg
getbreedCats breed_id =
let headers = [ Http.header "x-api-key" api_key ]
in
Http.request
{ body = Http.emptyBody
, method="GET"
, url = "https://api.thecatapi.com/v1/images/search?breed_id="++breed_id
, expect = Http.expectJson GotList breedListDecoder
, headers = headers
, timeout = Nothing
, tracker = Nothing
}
breedItemDecoder: Decoder Breed
breedItemDecoder =
JD.map3 Breed
(field "id" string)
(field "name" string)
(field "description" string)
breedListDecoder: Decoder (List Breed)
breedListDecoder =
JD.list breedItemDecoder