-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quote.elm
139 lines (94 loc) · 2.74 KB
/
Quote.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
module Quote exposing (..)
import Html exposing (..)
import Line
import Http exposing (RawError, Response, send, defaultSettings, string)
import Task
import Json.Decode as Json
import Json.Encode exposing (..)
-- MODEL
type alias Model =
List Line.Model
init : List Line.Model -> Model
init lines =
lines
-- UPDATE
type Msg
= SaveQuote
| SaveSucceeded (List Int)
| SaveFail Http.Error
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
SaveQuote ->
( model, getQuoteId model )
SaveSucceeded quoteId ->
( model, Cmd.none )
SaveFail _ ->
( model, Cmd.none )
-- VIEW
view : Model -> Html Msg
view model =
div []
[ text "Hoagies" ]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- HTTP
toValue : Int -> Line.Model -> Value
toValue quoteId line =
Json.Encode.object
[ ( "speaker", Json.Encode.string line.speaker )
, ( "words", Json.Encode.string line.words )
, ( "quotation_id", Json.Encode.int quoteId )
]
linesJson : Int -> Model -> String
linesJson quoteId lines =
let
lineValues =
list (List.map (toValue quoteId) lines)
in
encode 0 lineValues
postPreferRepresentation : String -> Http.Body -> Platform.Task Http.Error Int
postPreferRepresentation url body =
Http.fromJson decodeQuoteId
<| send defaultSettings
{ verb = "POST"
, headers =
[ ( "Prefer", "return=representation" )
, ( "Content-Type", "application/json" )
]
, url = url
, body = body
}
postLines : String -> Http.Body -> Platform.Task Http.Error (List Int)
postLines url body =
Http.fromJson decodeLineIds
<| send defaultSettings
{ verb = "POST"
, headers =
[ ( "Prefer", "return=representation" )
, ( "Content-Type", "application/json" )
]
, url = url
, body = body
}
getQuoteId : Model -> Cmd Msg
getQuoteId model =
let
url =
"//limitless-tundra-10904.herokuapp.com/quotations"
url2 =
"//limitless-tundra-10904.herokuapp.com/lines"
body =
Http.string """{"created_at": "now()"}"""
in
Task.perform SaveFail
SaveSucceeded
((postPreferRepresentation url body) `Task.andThen` (\theQuoteId -> postLines url2 (Http.string (linesJson theQuoteId model))))
decodeQuoteId : Json.Decoder Int
decodeQuoteId =
Json.at [ "id" ] Json.int
decodeLineIds : Json.Decoder (List Int)
decodeLineIds =
Json.list (Json.at [ "id" ] Json.int)