-- | Utility functions for use defining autodocodec codecs.
module Hasura.Metadata.DTO.Utils (versionField, optionalVersionField) where

import Autodocodec
  ( Codec (EqCodec),
    ObjectCodec,
    optionalFieldWith',
    requiredFieldWith',
    scientificCodec,
    (.=),
  )
import Data.Scientific (Scientific)
import Hasura.Prelude

-- | Defines a required object field named @version@ that must have the given
-- integer value. On serialization the field will have the given value
-- automatically. On deserialization parsing will fail unless the field has the
-- exact given value.
versionField :: Integer -> ObjectCodec a Scientific
versionField :: Integer -> ObjectCodec a Scientific
versionField Integer
v = Text
-> ValueCodec Scientific Scientific
-> ObjectCodec Scientific Scientific
forall input output.
Text -> ValueCodec input output -> ObjectCodec input output
requiredFieldWith' Text
"version" (Scientific
-> ValueCodec Scientific Scientific
-> ValueCodec Scientific Scientific
forall input.
(Show input, Eq input) =>
input -> JSONCodec input -> JSONCodec input
EqCodec Scientific
n ValueCodec Scientific Scientific
scientificCodec) ObjectCodec Scientific Scientific
-> (a -> Scientific) -> ObjectCodec a Scientific
forall oldInput output newInput.
ObjectCodec oldInput output
-> (newInput -> oldInput) -> ObjectCodec newInput output
.= Scientific -> a -> Scientific
forall a b. a -> b -> a
const Scientific
n
  where
    n :: Scientific
n = Integer -> Scientific
forall a. Num a => Integer -> a
fromInteger Integer
v

-- | Defines an optional object field named @version@ that must have the given
-- integer value if the field is present. On serialization the field will have
-- the given value automatically. On deserialization parsing will fail unless
-- the field has the exact given value, or is absent.
optionalVersionField :: Integer -> ObjectCodec a (Maybe Scientific)
optionalVersionField :: Integer -> ObjectCodec a (Maybe Scientific)
optionalVersionField Integer
v =
  Text
-> ValueCodec Scientific Scientific
-> ObjectCodec (Maybe Scientific) (Maybe Scientific)
forall input output.
Text
-> ValueCodec input output
-> ObjectCodec (Maybe input) (Maybe output)
optionalFieldWith' Text
"version" (Scientific
-> ValueCodec Scientific Scientific
-> ValueCodec Scientific Scientific
forall input.
(Show input, Eq input) =>
input -> JSONCodec input -> JSONCodec input
EqCodec Scientific
n ValueCodec Scientific Scientific
scientificCodec) ObjectCodec (Maybe Scientific) (Maybe Scientific)
-> (a -> Maybe Scientific) -> ObjectCodec a (Maybe Scientific)
forall oldInput output newInput.
ObjectCodec oldInput output
-> (newInput -> oldInput) -> ObjectCodec newInput output
.= Maybe Scientific -> a -> Maybe Scientific
forall a b. a -> b -> a
const (Scientific -> Maybe Scientific
forall a. a -> Maybe a
Just Scientific
n)
  where
    n :: Scientific
n = Integer -> Scientific
forall a. Num a => Integer -> a
fromInteger Integer
v