unkai-core-0.1.0.0: src/Unkai/Data/JSON.hs
-- |
-- Module : Unkai.Data.JSON
-- Copyright : (c) 2015-2022 Brendan Hay <brendan.g.hay@gmail.com>
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Nadeem Bitar <nadeem@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
module Unkai.Data.JSON
( Value,
AsText (..),
PatchField (..),
patchField,
parsePatchField,
parseJSONObject,
parseJSONText,
toJSONText,
-- * Re-exports
FromJSON (..),
FromJSONKey (..),
ToJSON (..),
ToJSONKey (..),
withObject,
emptyObject,
object,
(.=),
(.:),
(.:?),
(.!=),
)
where
import Data.Aeson
import Data.Aeson.Types
import Data.Text qualified as Text
import Web.HttpApiData (FromHttpApiData (..), ToHttpApiData (..))
import Data.Aeson.KeyMap (KeyMap)
import Data.Aeson.KeyMap qualified as KeyMap
-- | A field in a JSON merge-style patch. 'Omit' leaves it alone,
-- 'Set' assigns a value, and 'Clear' sends an explicit null.
data PatchField a = Omit | Set a | Clear
deriving stock (Eq, Show, Functor)
patchField :: (a -> Value) -> Key -> PatchField a -> Maybe Pair
patchField encodeValue key = \case
Omit -> Nothing
Set value -> Just (key, encodeValue value)
Clear -> Just (key, Null)
parsePatchField :: (Value -> Parser a) -> Key -> KeyMap Value -> Parser (PatchField a)
parsePatchField decodeValue key fields = case KeyMap.lookup key fields of
Nothing -> pure Omit
Just Null -> pure Clear
Just value -> Set <$> decodeValue value
newtype AsText a = AsText {fromAsText :: a}
deriving stock (Eq, Ord, Read, Show)
deriving newtype (Num, Fractional, ToHttpApiData, FromHttpApiData)
instance (FromJSON a, FromHttpApiData a) => FromJSON (AsText a) where
parseJSON (String s) = either (fail . Text.unpack) (pure . AsText) (parseQueryParam s)
parseJSON o = AsText <$> parseJSON o
instance (ToHttpApiData a) => ToJSON (AsText a) where
toJSON (AsText x) = String (toQueryParam x)
parseJSONObject :: (FromJSON a) => KeyMap Value -> Parser a
parseJSONObject = parseJSON . toJSON
parseJSONText :: (FromHttpApiData a) => String -> Value -> Parser a
parseJSONText n = withText n (either (fail . f) pure . parseQueryParam)
where
f x = n ++ " - " ++ Text.unpack x
toJSONText :: (ToHttpApiData a) => a -> Value
toJSONText = String . toQueryParam