Skip to content

Modelling sum types #80

Description

@commandodev

How do you go about expressing a sum type like this:

data WithdrawlResult =
    WithdrawlError ClientError   -- ^ Error with http client error
  | WithdrawlSuccess Transaction -- ^ Success with transaction details
  deriving (Show, Typeable, Generic)

instance ToJSON WithdrawlResult where
    toJSON (WithdrawlSuccess txn) =
        object ["success" .= txn]
    toJSON (WithdrawlError err) =
        object ["error" .= show err]

wdDesc :: Text
wdDesc = "An object with either a success field containing the transaction or "
      <> "an error field containing the ClientError from the wallet as a string"

instance ToSchema WithdrawlResult where
    declareNamedSchema _ = do
        txnSchema <- declareSchemaRef (Proxy :: Proxy Transaction)
        errSchema <- declareSchemaRef (Proxy :: Proxy String)
        return $ NamedSchema (Just "WithdrawlResult") $ mempty
          & type_ .~ SwaggerObject
          & enum_ ?~ [ object ["success" .= toJSON txnSchema]
                               , object ["error"   .= toJSON errSchema]
                               ]
          & properties .~ (mempty
               & at "success" ?~ txnSchema
               & at "error" ?~ errSchema)
          & description .~ (Just $ wdDesc)

Ideally I'd want to express that I'm expecting a JSON object with either { success: {...}} or { error: "Some message" } I can't quite figure out how to do that...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions