Created
October 22, 2015 17:34
-
-
Save kellymclaughlin/32f9d34eff3354d55025 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-- This instance does a lot with a small amount of code so this is a | |
short explanation of what is going on. Once we know we have a JSON | |
Object the next thing to determine before more parsing is the type of | |
event we are dealing with. To determine this we use some handy Lens | |
helpers for dealing with JSON from Data.Aeson.Lens to traverse the | |
document to where the type should be and return a `Maybe Text`. We can | |
then pass this result right to the `toEventType` function using the | |
Monad bind operator. If all goes well we now have the information to | |
proceed with parsing the event and if something has gone wrong we have | |
`Nothing`. We use `fmap` to apply `parseJSON v` to the `eventType` | |
result. This is done inside a call to `maybe` to avoid having to write | |
a `if` or `case` statement to handle the possible states of | |
`eventType`. --} | |
instance FromJSON EventType where | |
parseJSON v@(Object _) = | |
maybe (fail "Unknown event type") (flip fmap (parseJSON v)) eventType | |
where typeField x = x ^? _Value.key "contents"._Value.key "type"._String | |
eventType = typeField v >>= toEventType | |
parseJSON _ = fail "Invalid event format" | |
toEventType :: T.Text -> Maybe (ElementDetails -> EventType) | |
toEventType "element_connected" = Just ElementConnect | |
toEventType "element_connection_failure" = Just ElementConnectFail | |
toEventType _ = Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment