Skip to content

Add a combinator for decoding maybe fields #17

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

Merged
merged 1 commit into from
Aug 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/Data/Argonaut/Decode/Combinators.purs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Prelude
import Data.Argonaut.Core (JObject)
import Data.Argonaut.Decode.Class (class DecodeJson, decodeJson)
import Data.Either (Either(..))
import Data.Maybe (maybe)
import Data.Maybe (Maybe(Just, Nothing), maybe)
import Data.StrMap as SM

getField :: forall a. DecodeJson a => JObject -> String -> Either String a
Expand All @@ -16,3 +16,14 @@ getField o s =
(SM.lookup s o)

infix 7 getField as .?

getFieldOptional :: forall a. DecodeJson a => JObject -> String -> Either String (Maybe a)
getFieldOptional o s =
maybe
(pure Nothing)
decode
(SM.lookup s o)
where
decode json = Just <$> decodeJson json

infix 7 getFieldOptional as .??
3 changes: 3 additions & 0 deletions test/Test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ data User
| Guest String
| Registered
{ name :: String
, bio :: Maybe String
, age :: Int
, balance :: Number
, banned :: Boolean
Expand All @@ -169,6 +170,7 @@ genericsCheck = do
logShow $ gEncodeJson $ Guest "guest's handle"
logShow $ gEncodeJson $ Registered
{ name: "user1"
, bio: Just "Ordinary User"
, age: 5
, balance: 26.6
, banned: false
Expand All @@ -178,6 +180,7 @@ genericsCheck = do
, Guest "someGuest"
, Registered
{ name: "user2"
, bio: Nothing
, age: 6
, balance: 32.1
, banned: false
Expand Down