blob: 9bf2008f0474b486573de1fdc359d4e2c9e068ae (
plain)
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
|
module ServerCommunication
( Communication(..)
, sendRequest
, serverCommunications
) where
import Signal
import Task as Task exposing (Task)
import Http
import Json.Decode exposing (..)
import Date
import Model.Message exposing (messageDecoder)
import Model.Payment exposing (PaymentId)
import Update as U
import Update.SignIn exposing (..)
import Update.Payment as UP
type Communication =
NoCommunication
| SignIn String
| AddPayment String Int
| DeletePayment PaymentId
| SignOut
serverCommunications : Signal.Mailbox Communication
serverCommunications = Signal.mailbox NoCommunication
sendRequest : Communication -> Task Http.RawError U.Action
sendRequest communication =
case getRequest communication of
Nothing ->
Task.succeed U.NoOp
Just request ->
Http.send Http.defaultSettings request
|> Task.map (communicationToAction communication)
getRequest : Communication -> Maybe Http.Request
getRequest communication =
case communication of
NoCommunication ->
Nothing
SignIn login ->
Just (simplePost ("/signIn?login=" ++ login))
AddPayment name cost ->
Just (simplePost ("/payment/add?name=" ++ name ++ "&cost=" ++ (toString cost)))
DeletePayment paymentId ->
Just (simplePost ("payment/delete?id=" ++ paymentId))
SignOut ->
Just (simplePost "/signOut")
simplePost : String -> Http.Request
simplePost url =
{ verb = "post"
, headers = []
, url = url
, body = Http.empty
}
communicationToAction : Communication -> Http.Response -> U.Action
communicationToAction communication response =
if response.status == 200
then
case communication of
NoCommunication ->
U.NoOp
SignIn login ->
U.UpdateSignIn (ValidLogin login)
AddPayment name cost ->
decodeResponse
response
(\id -> U.UpdatePayment (UP.AddPayment id name cost))
DeletePayment id ->
U.UpdatePayment (UP.Remove id)
SignOut ->
U.GoSignInView
else
decodeResponse
response
(\error ->
case communication of
SignIn _ ->
U.UpdateSignIn (ErrorLogin error)
_ ->
U.NoOp
)
decodeResponse : Http.Response -> (String -> U.Action) -> U.Action
decodeResponse response responseToAction =
case response.value of
Http.Text text ->
case decodeString messageDecoder text of
Ok x ->
responseToAction x
Err _ ->
U.NoOp
Http.Blob _ ->
U.NoOp
|