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
1 changed files with 5 additions and 2 deletions

View File

@ -37,10 +37,13 @@ import qualified Hanafuda.KoiKoi as KoiKoi (
, Score, Scores, Source(..), Step(..), Yaku(..)
)
import Hanafuda.Player (Player(..), Players(..))
import Text.Read (readMaybe)
instance IDType a => FromJSON (ID a) where
parseJSON = withText decoding (return . read . Text.unpack)
where decoding = let Prefix p = (prefix :: Prefix a) in p ++ "ID"
parseJSON = withText decoding (safeRead . Text.unpack)
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
fromJSONKey = FromJSONKeyText (read . Text.unpack)
instance IDType a => ToJSON (ID a) where