packages feed

keiro-dsl-0.2.0.0: test/conformance-skeletons/SkelAggregate/Generated/MyService/Thing/Codec.hs

{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}

-- @generated by keiro-dsl; do not edit. Regenerated from the .keiro spec.
module SkelAggregate.Generated.MyService.Thing.Codec (
    thingCodec,
    parseThingEvent,
    encodeThingEvent,
) where

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

thingCodec :: Codec ThingEvent
thingCodec =
    Codec
        { eventTypes = EventType "ThingCompleted" :| []
        , eventType = \case
            ThingCompleted{} -> EventType "ThingCompleted"
        , schemaVersion = 1
        , encode = encodeThingEvent
        , decode = parseThingEvent
        , upcasters = []
        }

encodeThingEvent :: ThingEvent -> Value
encodeThingEvent = \case
    ThingCompleted payload ->
        object
            [ "kind" .= ("ThingCompleted" :: Text)
            , "thingId" .= thingIdText payload.thingId
            , "attempt" .= payload.attempt
            ]

parseThingEvent :: EventType -> Value -> Either Text ThingEvent
parseThingEvent (EventType tag) = mapLeftText . parseEither (withObject "ThingEvent" go)
  where
    go o = do
        case tag of
            "ThingCompleted" ->
                ThingCompleted <$> (ThingCompletedData <$> (ThingId <$> o .: "thingId") <*> o .: "attempt")
            _ -> fail "unknown event type"

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