-- | This module provides helper definitions for "Data.Aeson".
module Haspara.Internal.Aeson where

import qualified Data.Aeson as Aeson
import qualified Data.Char as C
import Data.List (stripPrefix)
import Data.Maybe (fromMaybe)


-- | Common Aeson encoding/decoding options.
commonAesonOptions :: String -> Aeson.Options
commonAesonOptions :: String -> Options
commonAesonOptions String
prefix =
  Options
Aeson.defaultOptions
    { Aeson.omitNothingFields = True
    , Aeson.fieldLabelModifier = \String
l -> Char -> String -> String
Aeson.camelTo2 Char
'_' (String -> String)
-> (Maybe String -> String) -> Maybe String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
l (Maybe String -> String) -> Maybe String -> String
forall a b. (a -> b) -> a -> b
$ String -> String -> Maybe String
forall a. Eq a => [a] -> [a] -> Maybe [a]
stripPrefix String
prefix String
l
    , Aeson.constructorTagModifier = \String
l -> Char -> String -> String
Aeson.camelTo2 Char
'_' (String -> String)
-> (Maybe String -> String) -> Maybe String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
l (Maybe String -> String) -> Maybe String -> String
forall a b. (a -> b) -> a -> b
$ String -> String -> Maybe String
forall a. Eq a => [a] -> [a] -> Maybe [a]
stripPrefix String
prefix String
l
    , Aeson.sumEncoding =
        Aeson.TaggedObject
          { Aeson.tagFieldName = "type"
          , Aeson.contentsFieldName = "value"
          }
    }


-- | Aeson encoding/decoding options for uppercase constructor tag modifiers
aesonOptionsForSingleTag :: String -> Aeson.Options
aesonOptionsForSingleTag :: String -> Options
aesonOptionsForSingleTag String
prefix =
  Options
Aeson.defaultOptions
    { Aeson.constructorTagModifier = \String
l -> (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Char -> Char
C.toUpper (String -> String)
-> (Maybe String -> String) -> Maybe String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> String -> String
Aeson.camelTo2 Char
'_' (String -> String)
-> (Maybe String -> String) -> Maybe String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
l (Maybe String -> String) -> Maybe String -> String
forall a b. (a -> b) -> a -> b
$ String -> String -> Maybe String
forall a. Eq a => [a] -> [a] -> Maybe [a]
stripPrefix String
prefix String
l
    }