Skip to content

Instantly share code, notes, and snippets.

@emptyflask
Created September 12, 2017 02:38
Show Gist options
  • Select an option

  • Save emptyflask/131edb2f45d497150a4011f6c05828a4 to your computer and use it in GitHub Desktop.

Select an option

Save emptyflask/131edb2f45d497150a4011f6c05828a4 to your computer and use it in GitHub Desktop.
module Api exposing (..)
import Json.Decode as Json
type Event
= ChatEvent
| StateEvent
type alias Api =
{ event : String
, data : Event
}
type alias Chat =
{ player : String
, line : String
}
type alias State =
{ seats : List Seat
}
type alias Seat =
{ player : Player
, direction : String
}
type alias Player =
{ name : String
, wins : Int
}
apiDecoder : Json.Decoder Api
apiDecoder =
Json.field "event" Json.string
|> Json.andThen eventDecoder
eventDecoder : String -> Json.Decoder Api
eventDecoder event =
case event of
"chat" ->
chatDecoder
"state" ->
stateDecoder
chatDecoder : Json.Decoder Chat
chatDecoder =
Json.map2 Chat
(Json.field "player" Json.string)
(Json.field "line" Json.string)
stateDecoder : Json.Decoder (List Seat)
stateDecoder =
Json.field "seats" (Json.list seatDecoder)
seatDecoder : Json.Decoder Seat
seatDecoder =
Json.map2 Seat
(Json.field "player" playerDecoder)
(Json.field "direction" Json.string)
playerDecoder : Json.Decoder Player
playerDecoder =
Json.map2 Player
(Json.field "name" Json.string)
(Json.field "wins" Json.int)
chat_json =
"""
{
"event": "chat",
"data": {
"player": "Abilene",
"line": "woof"
}
}
"""
state_json =
"""
{
"event": "state",
"data": {
"seats": [
{
"player": {
"name": "Erik",
"hand": TileCollection,
"melds": [],
"discards": [],
"wins": 0
},
"direction": "east"
},
{
"player": {
"name": "Jon",
"hand": TileCollection,
"melds": [],
"discards": [],
"wins": 0
},
"direction": "north"
},
{
"player": {
"name": "Bethany",
"hand": TileCollection,
"melds": [],
"discards": [],
"wins": 0
},
"direction": "west"
},
{
"player": {
"name": "Jess",
"hand": TileCollection,
"melds": [],
"discards": [],
"wins": 0
},
"direction": "south"
}
]
}
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment