Skip to content

Commit

Permalink
WriteForeign for newtyped maps
Browse files Browse the repository at this point in the history
  • Loading branch information
nwolverson committed Apr 7, 2020
1 parent da85a9a commit 54becc3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Simple/JSON.purs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,10 @@ instance writeForeignMaybe :: WriteForeign a => WriteForeign (Maybe a) where
instance writeForeignNullable :: WriteForeign a => WriteForeign (Nullable a) where
writeImpl = maybe (unsafeToForeign $ toNullable Nothing) writeImpl <<< toMaybe

instance writeForeignObject :: WriteForeign a => WriteForeign (Map String a) where
instance writeForeignMap :: WriteForeign a => WriteForeign (Map String a) where
writeImpl = unsafeToForeign <<< map writeImpl

else instance writeForeignNewtypeMap :: (Newtype b String, WriteForeign a) => WriteForeign (Map b a) where
writeImpl = unsafeToForeign <<< map writeImpl

instance recordWriteForeign ::
Expand Down
15 changes: 15 additions & 0 deletions test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Data.Either (Either(..), either, fromLeft, isRight)
import Data.List (List(..), (:))
import Data.List.NonEmpty (NonEmptyList(..))
import Data.Maybe (Maybe)
import Data.Newtype (class Newtype)
import Data.NonEmpty (NonEmpty(..))
import Data.Nullable (Nullable)
import Data.Variant (Variant)
Expand Down Expand Up @@ -59,6 +60,14 @@ type MyTestStrMap =
, b :: Map String Int
}

newtype AlsoAString = AlsoAString String
derive instance alsoAStringNewtype :: Newtype AlsoAString _

type MyTestStrMapNewtype =
{ a :: Int
, b :: Map AlsoAString Int
}

type MyTestMaybe =
{ a :: Maybe String
}
Expand Down Expand Up @@ -167,6 +176,12 @@ main = do
{ "a": 1, "b": {"asdf": 1, "c": 2} }
"""

-- "works with JSON containing Map field with newtyped keys"
roundtrips (Proxy :: Proxy MyTestStrMapNewtype) """
{ "a": 1, "b": {"asdf": 1, "c": 2} }
"""


-- "works with Maybe field and existing value"
roundtrips (Proxy :: Proxy MyTestMaybe) """
{ "a": "foo" }
Expand Down

0 comments on commit 54becc3

Please sign in to comment.