Switch to Aeson generic parsing

This commit is contained in:
Joscha 2020-02-07 08:56:41 +00:00
parent 111721e3b0
commit 4b0c40bf2b

View file

@ -1,4 +1,6 @@
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This module contains all the types found in the API. -- | This module contains all the types found in the API.
@ -18,8 +20,10 @@ import Control.Applicative
import Control.Monad import Control.Monad
import Data.Aeson import Data.Aeson
import Data.Aeson.Types import Data.Aeson.Types
import Data.Char
import qualified Data.HashMap.Strict as Map import qualified Data.HashMap.Strict as Map
import qualified Data.Text as T import qualified Data.Text as T
import GHC.Generics
{- Common -} {- Common -}
@ -32,46 +36,21 @@ data Node = Node
, nodeDelete :: Bool , nodeDelete :: Bool
, nodeReply :: Bool , nodeReply :: Bool
, nodeChildren :: Map.HashMap NodeId Node , nodeChildren :: Map.HashMap NodeId Node
} deriving (Show) } deriving (Show, Generic)
nodeOptions :: Options
nodeOptions = defaultOptions{fieldLabelModifier = map toLower . drop 4}
instance ToJSON Node where instance ToJSON Node where
toJSON node = object toJSON = genericToJSON nodeOptions
[ "text" .= nodeText node toEncoding = genericToEncoding nodeOptions
, "act" .= nodeAct node
, "edit" .= nodeEdit node
, "delete" .= nodeDelete node
, "reply" .= nodeReply node
, "children" .= nodeChildren node
]
toEncoding node = pairs
( "text" .= nodeText node
<> "act" .= nodeAct node
<> "edit" .= nodeEdit node
<> "delete" .= nodeDelete node
<> "reply" .= nodeReply node
<> "children" .= nodeChildren node
)
instance FromJSON Node where instance FromJSON Node where
parseJSON v = parseJSON v >>= \o -> Node parseJSON = genericParseJSON nodeOptions
<$> o .: "text"
<*> o .: "act"
<*> o .: "edit"
<*> o .: "delete"
<*> o .: "reply"
<*> o .: "children"
newtype Path = Path newtype Path = Path
{ pathElements :: [NodeId] { pathElements :: [NodeId]
} deriving (Show, Eq) } deriving (Show, Eq, ToJSON, FromJSON)
instance ToJSON Path where
toJSON = toJSON . pathElements
toEncoding = toEncoding . pathElements
instance FromJSON Path where
parseJSON v = Path <$> parseJSON v
parsePacket :: Value -> T.Text -> (Object -> Parser a) -> Parser a parsePacket :: Value -> T.Text -> (Object -> Parser a) -> Parser a
parsePacket value packetType parser = parseJSON value >>= \o -> do parsePacket value packetType parser = parseJSON value >>= \o -> do