Make reading IDs safe and provide useful debug messages

This commit is contained in:
Tissevert 2019-12-27 17:55:42 +01:00
parent c6352a9669
commit 1dd31d7091

View file

@ -37,10 +37,13 @@ import qualified Hanafuda.KoiKoi as KoiKoi (
, Score, Scores, Source(..), Step(..), Yaku(..) , Score, Scores, Source(..), Step(..), Yaku(..)
) )
import Hanafuda.Player (Player(..), Players(..)) import Hanafuda.Player (Player(..), Players(..))
import Text.Read (readMaybe)
instance IDType a => FromJSON (ID a) where instance IDType a => FromJSON (ID a) where
parseJSON = withText decoding (return . read . Text.unpack) parseJSON = withText decoding (safeRead . Text.unpack)
where decoding = let Prefix p = (prefix :: Prefix a) in p ++ "ID" where
decoding = let Prefix p = (prefix :: Prefix a) in p ++ "ID"
safeRead s = maybe (fail $ "Not an ID: '" ++ s ++ "'") return $ readMaybe s
instance IDType a => FromJSONKey (ID a) where instance IDType a => FromJSONKey (ID a) where
fromJSONKey = FromJSONKeyText (read . Text.unpack) fromJSONKey = FromJSONKeyText (read . Text.unpack)
instance IDType a => ToJSON (ID a) where instance IDType a => ToJSON (ID a) where