module Api.Player exposing (Player, Wealth, blankPlayer, get, list, playerDecoder, wealthDecoder) import Http import Json.Decode as D exposing (Decoder, int, string) type alias Player = { id : Int , name : String , debt : Int , wealth : Wealth } playerDecoder : Decoder Player playerDecoder = D.map4 Player (D.field "id" int) (D.field "name" string) (D.field "debt" int) wealthDecoder type alias Wealth = { cp : Int , sp : Int , gp : Int , pp : Int } wealthDecoder : Decoder Wealth wealthDecoder = D.map4 Wealth (D.field "cp" int) (D.field "sp" int) (D.field "gp" int) (D.field "pp" int) -- PLAYERS blankPlayer = Player 0 "Loot-a-lot" 0 (Wealth 0 0 0 0) get : (Result Http.Error Player -> msg) -> Int -> Cmd msg get toMsg id = Http.get { url = "api/players/" ++ String.fromInt id ++ "/" , expect = Http.expectJson toMsg (valueDecoder playerDecoder) } list : (List Player -> msg) -> Cmd msg list toMsg = let parseResponse : Result Http.Error (List Player) -> msg parseResponse response = case response of Ok players -> toMsg players Err e -> let _ = Debug.log "Player's list fetch error" (Debug.toString e) in toMsg [] in Http.get { url = "api/players/" , expect = Http.expectJson parseResponse (valueDecoder <| D.list playerDecoder) } valueDecoder : Decoder a -> Decoder a valueDecoder thenDecoder = D.field "value" thenDecoder