autodocodec icon indicating copy to clipboard operation
autodocodec copied to clipboard

Documentation on how to use type fields

Open NorfairKing opened this issue 3 years ago • 0 comments

Using a non-monadic parser means you cannot case-match on a field to determine what to parse next. BUT we can still use type fields like this:

data NSCheck = NSCheck
  { nsCheckDomain :: !Domain,
    nsCheckAddresses :: ![Domain]
  }
  deriving stock (Show, Eq, Generic)
  deriving (FromJSON, ToJSON) via (Autodocodec NSCheck)

instance Validity NSCheck

instance HasCodec NSCheck where
  codec =
    object "NSCheck" $
      typeField "ns" NSCheck
        <*> domainField .= nsCheckDomain
        <*> singleOrListFieldWith "value" "values" domainCodec "domains" .= nsCheckAddresses

typeField :: Text -> a -> ObjectCodec b a
typeField typeName a =
  a <$ requiredFieldWith' "type" (literalTextCodec typeName) .= const typeName

This could be documented better.

NorfairKing avatar Dec 28 '21 11:12 NorfairKing