packages feed

keiro-dsl-0.12.0.0: test/conformance-domain-outcomes/Generated/DomainOutcomes/Reservation/Codec.hs

{-# LANGUAGE OverloadedRecordDot #-}
-- @generated by keiro-dsl 0.12.0.0 (language keiro-dsl 5) from aggregate Reservation; do not edit.
module Generated.DomainOutcomes.Reservation.Codec (
    reservationCodec,
    parseReservationEvent,
    encodeReservationEvent,
) where

import Generated.DomainOutcomes.Reservation.Domain
import Data.Aeson (Value, object, withObject, (.:), (.=))
import Data.Aeson.Types (parseEither)
import Data.List.NonEmpty (NonEmpty (..))
import Data.List.NonEmpty qualified as NonEmpty
import Data.Text (Text)
import qualified Data.Text as T
import Keiro.Codec (Codec (..), EventType (..))





reservationEventTypes :: NonEmpty EventType
reservationEventTypes = EventType "Cancelled" :| []

reservationCodec :: Codec ReservationEvent
reservationCodec =
  Codec
    { eventTypes = reservationEventTypes
    , eventType = \case
        Cancelled{} -> EventType "Cancelled"
    , schemaVersion = 1
    , encode = encodeReservationEvent
    , decode = parseReservationEvent
    , upcasters = []
    }

encodeReservationEvent :: ReservationEvent -> Value
encodeReservationEvent = \case
  Cancelled payload ->
    object
      [ "kind" .= ("Cancelled" :: Text)
      , "requestId" .= payload.requestId
      ]

parseReservationEvent :: EventType -> Value -> Either Text ReservationEvent
parseReservationEvent (EventType tag) = mapLeftText . parseEither (withObject "ReservationEvent" go)
  where
    go o = do
      case tag of
        "Cancelled" ->
          Cancelled
            <$> ( CancelledData
                    <$> o .: "requestId"
                )
        _ -> fail ("unknown event type " <> show tag <> "; expected one of: " <> renderExpectedEventTypes reservationEventTypes)

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

renderExpectedEventTypes :: NonEmpty EventType -> String
renderExpectedEventTypes =
  T.unpack
    . T.intercalate ", "
    . map (\(EventType eventTypeName) -> eventTypeName)
    . NonEmpty.toList