{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Worldcup.Games (Game(..), parseGames) where import Data.Aeson import Data.Aeson.Types data Game = Game { gamePlayAt :: String, gameRoundId :: Int, gameTeam1Id :: Int, gameTeam2Id :: Int, gameScore1 :: Value, gameScore2 :: Value, gameScore1et :: Value, gameScore2et :: Value, gameScore1p :: Value, gameScore2p :: Value } deriving (Show) instance ToJSON Game where toJSON Game{..} = object [ "ts" .= gamePlayAt, "rId" .= gameRoundId, "t1" .= gameTeam1Id, "t2" .= gameTeam2Id, "s1" .= gameScore1, "se1" .= gameScore1et, "sp1" .= gameScore1p, "s2" .= gameScore2, "se2" .= gameScore2et, "sp2" .= gameScore2p ] instance FromJSON Game where parseJSON = withObject "game" $ \o -> do gameRoundId <- o .: "round_id" gameTeam1Id <- o .: "team1_id" gameTeam2Id <- o .: "team2_id" gamePlayAt <- o .: "play_at" gameScore1 <- o .: "score1" gameScore2 <- o .: "score2" gameScore1et <- o .: "score1et" gameScore2et <- o .: "score2et" gameScore1p <- o .: "score1p" gameScore2p <- o .: "score2p" return Game{..} parseGames :: Either String [Value] -> [Game] parseGames (Left x) = error x parseGames (Right xs) = foldl reduce [] xs where reduce acc x = case (parseEither parseJSON x :: Either String Game) of (Left s) -> error s (Right v) -> v : acc