{-# OPTIONS_HADDOCK prune not-home #-}

{- |
Copyright   : (c) 2022 Tim Emiola
Maintainer  : Tim Emiola <adetokunbo@emio.la>
SPDX-License-Identifier: BSD3
-}
module KeyedVals.Handle.Codec.Aeson (
  -- * newtypes
  AesonOf (..),
) where

import Data.Aeson (
  FromJSON (..),
  ToJSON (..),
  eitherDecodeStrict',
  encode,
 )
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as Text
import KeyedVals.Handle.Codec (DecodeKV (..), EncodeKV (..))


{- | A deriving-via helper type for types that implement 'DecodeKV' and 'EncodeKV'
 using Aeson's 'FromJSON' and 'ToJSON' type classes.
-}
newtype AesonOf a = AesonOf {forall a. AesonOf a -> a
fromAesonOf :: a}


instance FromJSON a => DecodeKV (AesonOf a) where
  decodeKV :: Val -> Either Text (AesonOf a)
decodeKV = forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> Either a b
Left forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
Text.pack) (forall a b. b -> Either a b
Right forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> AesonOf a
AesonOf) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. FromJSON a => Val -> Either String a
eitherDecodeStrict'


instance ToJSON a => EncodeKV (AesonOf a) where
  encodeKV :: AesonOf a -> Val
encodeKV = ByteString -> Val
LBS.toStrict forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. ToJSON a => a -> ByteString
encode forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. AesonOf a -> a
fromAesonOf