Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation on how to use type fields #9

Closed
NorfairKing opened this issue Dec 28, 2021 · 4 comments
Closed

Documentation on how to use type fields #9

NorfairKing opened this issue Dec 28, 2021 · 4 comments

Comments

@NorfairKing
Copy link
Owner

NorfairKing commented Dec 28, 2021

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 NorfairKing closed this as not planned Won't fix, can't repro, duplicate, stale Mar 6, 2023
@NorfairKing
Copy link
Owner Author

PR welcome

@m1-s
Copy link

m1-s commented Apr 11, 2023

I do not understand this yet. So, typeField parses to NSCheck as long as type: "ns". But how can I make this parse to a different type when type contains a different value? If this is not possible, I do not get the purpose of typeField. Or is it just about ignoring the type field?

@m1-s
Copy link

m1-s commented Apr 11, 2023

Is there any other workaround, e.g. defining separate objects for each type and manually handle the case if multiple types are specified at the same time?

type: 
  type1: value1
  type2: value2

where only type1 or type2 may be specified but not both at the same time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants