summaryrefslogtreecommitdiffstats
path: root/src/Main.elm
blob: 9d55d9cff9f27db7add54e144bc5ea897e7095be (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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
port module Main exposing (..)

import Browser exposing (Document)
import Browser.Navigation exposing (Key)
import Config exposing (makeApiUrl)
import Html.Styled exposing (..)
import Html.Styled.Events exposing (onClick)
import Http
import Json.Decode exposing (Decoder, field, int, list, map2, map5, string)
import Json.Encode
import Pages.Feed exposing (feedView)
import Task
import Time
import Types exposing (Author, Model, Msg(..), Post)
import Url exposing (Url)


main : Program () Model Msg
main =
    Browser.application
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        , onUrlRequest = \_ -> NoOp
        , onUrlChange = \_ -> NoOp
        }



-- PORTS


port showAlert : String -> Cmd msg


port requestLogout : () -> Cmd msg



-- INIT


init : () -> Url -> Key -> ( Model, Cmd Msg )
init _ _ _ =
    ( { posts = Nothing
      , now = Time.millisToPosix 0
      , composeInputValue = ""
      }
    , Cmd.batch [ getPosts, Task.perform SetNowPosix Time.now ]
    )



-- UPDATE


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp ->
            ( model, Cmd.none )

        SetNowPosix now ->
            ( { model | now = now }, Cmd.none )

        RequestLogout ->
            ( model, requestLogout () )

        GetPosts ->
            ( model, getPosts )

        GotPosts (Result.Ok posts) ->
            ( { model | posts = Just posts }, Cmd.none )

        GotPosts (Result.Err httpErr) ->
            ( model
            , showAlert <| httpErrorToString httpErr
            )

        LikePost post ->
            ( model, likePost post )

        LikedPost (Result.Ok post) ->
            ( { model | posts = Just <| replaceMatchingPost post (Maybe.withDefault [] model.posts) }
            , Cmd.none
            )

        LikedPost (Result.Err httpErr) ->
            ( model
            , showAlert <| httpErrorToString httpErr
            )

        ComposeInputChanged value ->
            ( { model | composeInputValue = value }, Cmd.none )

        ComposePost ->
            ( model
            , if String.length model.composeInputValue > 0 then
                composePost model

              else
                Cmd.none
            )

        ComposedPost (Result.Ok post) ->
            ( { model
                | posts = Maybe.map (\posts -> post :: posts) model.posts
                , composeInputValue = ""
              }
            , Cmd.none
            )

        ComposedPost (Result.Err httpErr) ->
            ( model
            , showAlert <| httpErrorToString httpErr
            )


replaceMatchingPost : Post -> List Post -> List Post
replaceMatchingPost post posts =
    List.map
        (\p ->
            if p.id == post.id then
                post

            else
                p
        )
        posts


getPosts : Cmd Msg
getPosts =
    Http.get
        { url = makeApiUrl Config.ApiPosts
        , expect = Http.expectJson GotPosts postsDecoder
        }


likePost : Post -> Cmd Msg
likePost post =
    Http.request
        { method = "PATCH"
        , headers = []
        , url = makeApiUrl (Config.ApiLikePost post.id)
        , body =
            Http.jsonBody
                (Json.Encode.object
                    [ ( "likes", Json.Encode.int (post.likes + 1) ) ]
                )
        , expect = Http.expectJson LikedPost postDecoder
        , timeout = Nothing
        , tracker = Nothing
        }


composePost : Model -> Cmd Msg
composePost model =
    Http.post
        { url = makeApiUrl Config.ApiCompose
        , expect = Http.expectJson ComposedPost postDecoder
        , body =
            Http.jsonBody
                (Json.Encode.object
                    [ ( "content", Json.Encode.string model.composeInputValue )
                    , ( "createdAt", Json.Encode.int <| Time.posixToMillis model.now // 1000 )
                    , ( "likes", Json.Encode.int 0 )
                    , ( "author"
                      , Json.Encode.object
                            [ ( "id", Json.Encode.string "logged-in-user-id" )
                            , ( "name", Json.Encode.string "Logged in user" )
                            ]
                      )
                    ]
                )
        }


subscriptions : Model -> Sub Msg
subscriptions _ =
    Time.every 5000 SetNowPosix



-- JSON


decodeTime : Decoder Time.Posix
decodeTime =
    int
        |> Json.Decode.andThen
            (\ms ->
                Json.Decode.succeed <| Time.millisToPosix (ms * 1000)
            )


postsDecoder : Decoder (List Post)
postsDecoder =
    list postDecoder


postDecoder : Decoder Post
postDecoder =
    map5 Post
        (field "id" string)
        (field "content" string)
        (field "author"
            (map2 Author
                (field "id" string)
                (field "name" string)
            )
        )
        (field "createdAt" decodeTime)
        (field "likes" int)



-- VIEW


view : Model -> Document Msg
view model =
    { title = "Shoob book"
    , body = button [ onClick RequestLogout ] [ text "Logout" ] :: feedView model |> List.map toUnstyled
    }



-- UTILS


httpErrorToString : Http.Error -> String
httpErrorToString err =
    case err of
        Http.BadUrl url ->
            "URL {0} is invalid" |> templ [ url ]

        Http.Timeout ->
            "Request has timed out"

        Http.NetworkError ->
            "Unable to reach the server, check your network connection"

        Http.BadStatus status ->
            "Server responded with status {0}" |> templ [ String.fromInt status ]

        Http.BadBody msg ->
            msg


templ : List String -> String -> String
templ rs original =
    let
        templElement_ : ( Int, String ) -> String -> String
        templElement_ ( index, r ) orig_ =
            String.replace ("{" ++ String.fromInt index ++ "}") r orig_
    in
    List.indexedMap Tuple.pair rs
        |> List.foldl templElement_ original