haskell-servant / haskell-servant/servant-swagger
Modelling sum types
- Dominant language
- Haskell
- Stars
- 123
- Forks
- 34
- PR merge metrics
- No merged PRs in 30d
Description
How do you go about expressing a sum type like this:
```haskell
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...
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the ToSchema WithdrawlResult instance shown in the issue and inspect how existing sum types are represented in this project. Compare the generated Swagger schema with the requested success-or-error object shape; done means the schema clearly expresses either alternative and is covered by the project's relevant schema tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- haskell
- Domain
- api
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100