module Rel8.Type.JSONBEncoded ( JSONBEncoded(..) ) where

-- aeson
import Data.Aeson ( FromJSON, ToJSON, parseJSON, toJSON )
import Data.Aeson.Types ( parseEither )

-- base
import Data.Bifunctor ( first )
import Prelude

-- hasql
import qualified Hasql.Decoders as Hasql

-- rel8
import Rel8.Type ( DBType(..) )
import Rel8.Type.Information ( TypeInformation(..) )

-- text
import Data.Text ( pack )


-- | Like 'Rel8.JSONEncoded', but works for @jsonb@ columns.
newtype JSONBEncoded a = JSONBEncoded { JSONBEncoded a -> a
fromJSONBEncoded :: a }


instance (FromJSON a, ToJSON a) => DBType (JSONBEncoded a) where
  typeInformation :: TypeInformation (JSONBEncoded a)
typeInformation = TypeInformation :: forall a. (a -> PrimExpr) -> Value a -> String -> TypeInformation a
TypeInformation
    { encode :: JSONBEncoded a -> PrimExpr
encode = TypeInformation Value -> Value -> PrimExpr
forall a. TypeInformation a -> a -> PrimExpr
encode TypeInformation Value
forall a. DBType a => TypeInformation a
typeInformation (Value -> PrimExpr)
-> (JSONBEncoded a -> Value) -> JSONBEncoded a -> PrimExpr
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Value
forall a. ToJSON a => a -> Value
toJSON (a -> Value) -> (JSONBEncoded a -> a) -> JSONBEncoded a -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. JSONBEncoded a -> a
forall a. JSONBEncoded a -> a
fromJSONBEncoded
    , decode :: Value (JSONBEncoded a)
decode = (Value -> Either Text (JSONBEncoded a))
-> Value Value -> Value (JSONBEncoded a)
forall a b. (a -> Either Text b) -> Value a -> Value b
Hasql.refine ((String -> Text)
-> Either String (JSONBEncoded a) -> Either Text (JSONBEncoded a)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first String -> Text
pack (Either String (JSONBEncoded a) -> Either Text (JSONBEncoded a))
-> (Value -> Either String (JSONBEncoded a))
-> Value
-> Either Text (JSONBEncoded a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a -> JSONBEncoded a)
-> Either String a -> Either String (JSONBEncoded a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> JSONBEncoded a
forall a. a -> JSONBEncoded a
JSONBEncoded (Either String a -> Either String (JSONBEncoded a))
-> (Value -> Either String a)
-> Value
-> Either String (JSONBEncoded a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Value -> Parser a) -> Value -> Either String a
forall a b. (a -> Parser b) -> a -> Either String b
parseEither Value -> Parser a
forall a. FromJSON a => Value -> Parser a
parseJSON) Value Value
Hasql.jsonb
    , typeName :: String
typeName = String
"jsonb"
    }