Switch to json encoded meta data

Instead of parsing a comma separated list of photo urls, we retrieve a
json array of meta data (url, title, size).
This commit is contained in:
Alexander Kobjolke 2023-12-12 09:43:51 +01:00
parent e47f1d0449
commit a4501d5cb5
4 changed files with 174 additions and 44 deletions

View file

@ -5,6 +5,8 @@ import Html exposing (Html, button, div, h1, h3, img, input, label, text)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)
import Http
import Json.Decode as D exposing (Decoder)
import Json.Decode.Pipeline as D
import Random
@ -21,7 +23,18 @@ type alias Model =
type alias Photo =
{ url : String }
{ url : String
, size : Int
, title : String
}
photoDecoder : Decoder Photo
photoDecoder =
D.succeed Photo
|> D.required "url" D.string
|> D.required "size" D.int
|> D.optional "title" D.string "(untitled)"
type ThumbnailSize
@ -41,7 +54,7 @@ initialCommand : Cmd Message
initialCommand =
Http.get
{ url = "list"
, expect = Http.expectString GotPhotos
, expect = Http.expectJson GotPhotos (D.list photoDecoder)
}
@ -129,7 +142,7 @@ type Message
| ClickedSurpriseMe
| ClickedSize ThumbnailSize
| GotRandomPhoto Photo
| GotPhotos (Result Http.Error String)
| GotPhotos (Result Http.Error (List Photo))
update : Message -> Model -> ( Model, Cmd Message )
@ -160,17 +173,11 @@ update msg model =
GotRandomPhoto photo ->
( { model | status = selectUrl photo.url model.status }, Cmd.none )
GotPhotos (Ok str) ->
case String.split "," str of
(x :: _) as urls ->
let
photos =
List.map Photo urls
in
( { model | status = Loaded photos x }, Cmd.none )
GotPhotos (Ok ((firstPhoto :: _) as photos)) ->
( { model | status = Loaded photos firstPhoto.url }, Cmd.none )
[] ->
( { model | status = Errored ("No photos: " ++ str) }, Cmd.none )
GotPhotos (Ok []) ->
( { model | status = Errored "No photos!" }, Cmd.none )
GotPhotos (Err httpError) ->
( { model | status = Errored <| ("Failed to load photos: " ++ httpErrorToString httpError) }, Cmd.none )