packages feed

keiro-dsl-0.26.0.0: test/conformance-contract-rollout/before/Before/Generated/ContractRollout/Presence/Contract.hs

-- @generated by keiro-dsl 0.26.0.0 (language keiro-dsl 6) from contract presence; do not edit.
module Before.Generated.ContractRollout.Presence.Contract
  ( PresencePayload (..)
  , NotedData (..)
  , notesTopic
  , messageTypeOf
  , encodePresencePayload
  , parsePresencePayload
  ) where

import Data.Aeson (Value, object, withObject, withText, (.:), (.:?), (.=))
import Data.Aeson.Types (Parser, explicitParseField, parseEither)
import Data.Text (Text)
import qualified Data.Text as T

-- topic constants
notesTopic :: Text
notesTopic = "rollout.presence"

-- the closed payload set (discriminated by "messageType")
data NotedData = NotedData { subject :: !Text, note :: !(Maybe Text) }
  deriving stock (Eq, Show)

data PresencePayload = Noted !NotedData
  deriving stock (Eq, Show)

messageTypeOf :: PresencePayload -> Text
messageTypeOf = \case
  Noted {} -> "Noted"

encodePresencePayload :: PresencePayload -> Value
encodePresencePayload = \case
  Noted payload ->
    object
      ( [ "messageType" .= ("Noted" :: Text)
        , "subject" .= payload.subject
        ]
          <> ["note" .= value | Just value <- [payload.note]]
      )

parsePresencePayload :: Value -> Either Text PresencePayload
parsePresencePayload = mapLeftText . parseEither (withObject "PresencePayload" go)
  where
    go o = do
      kind <- explicitParseField (withText "messageType" validateMessageType) o "messageType"
      case kind of
        "Noted" ->
          Noted
            <$> ( NotedData
                    <$> o .: "subject"
                    <*> o .:? "note"
                )
        _ -> fail "validated message type was not handled"

mapLeftText :: Either String b -> Either Text b
mapLeftText = either (Left . T.pack) Right

validateMessageType :: Text -> Parser Text
validateMessageType kind
  | kind `elem` ["Noted"] = pure kind
  | otherwise = fail ("unknown message type " <> show kind <> "; expected one of: Noted")