2022-06-27 19:32:25 +03:00
|
|
|
-- | Utility functions for use defining autodocodec codecs.
|
2022-10-12 19:28:51 +03:00
|
|
|
module Hasura.Metadata.DTO.Utils
|
|
|
|
( codecNamePrefix,
|
|
|
|
fromEnvCodec,
|
|
|
|
versionField,
|
|
|
|
optionalVersionField,
|
|
|
|
)
|
|
|
|
where
|
2022-06-27 19:32:25 +03:00
|
|
|
|
|
|
|
import Autodocodec
|
|
|
|
( Codec (EqCodec),
|
2022-10-12 19:28:51 +03:00
|
|
|
JSONCodec,
|
2022-06-27 19:32:25 +03:00
|
|
|
ObjectCodec,
|
2022-10-12 19:28:51 +03:00
|
|
|
object,
|
2022-06-27 19:32:25 +03:00
|
|
|
optionalFieldWith',
|
2022-10-12 19:28:51 +03:00
|
|
|
requiredField',
|
2022-06-27 19:32:25 +03:00
|
|
|
requiredFieldWith',
|
|
|
|
scientificCodec,
|
|
|
|
(.=),
|
|
|
|
)
|
|
|
|
import Data.Scientific (Scientific)
|
2022-09-12 23:29:51 +03:00
|
|
|
import Data.Text qualified as T
|
|
|
|
import Data.Text.Extended qualified as T
|
2022-06-27 19:32:25 +03:00
|
|
|
import Hasura.Prelude
|
2022-09-12 23:29:51 +03:00
|
|
|
import Hasura.SQL.Tag (HasTag (backendTag), reify)
|
2022-06-27 19:32:25 +03:00
|
|
|
|
|
|
|
-- | 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 v = requiredFieldWith' "version" (EqCodec n scientificCodec) .= const n
|
|
|
|
where
|
|
|
|
n = fromInteger 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 v =
|
|
|
|
optionalFieldWith' "version" (EqCodec n scientificCodec) .= const (Just n)
|
|
|
|
where
|
|
|
|
n = fromInteger v
|
2022-09-12 23:29:51 +03:00
|
|
|
|
|
|
|
-- | Provides a title-cased name for a database kind, inferring the appropriate
|
|
|
|
-- database kind from type context.
|
|
|
|
codecNamePrefix :: forall b. (HasTag b) => Text
|
|
|
|
codecNamePrefix = T.toTitle $ T.toTxt $ reify $ backendTag @b
|
2022-10-12 19:28:51 +03:00
|
|
|
|
|
|
|
-- | Represents a text field wrapped in an object with a single property
|
|
|
|
-- named @from_env@.
|
|
|
|
--
|
|
|
|
-- Objects of this form appear in many places in the Metadata API. If we
|
|
|
|
-- reproduced this codec in each use case the OpenAPI document would have many
|
|
|
|
-- identical object definitions. Using a shared codec allows a single shared
|
|
|
|
-- reference.
|
|
|
|
fromEnvCodec :: JSONCodec Text
|
|
|
|
fromEnvCodec = object "FromEnv" $ requiredField' "from_env"
|