Skip to content

Commit 5c729f5

Browse files
committed
Review feedback, add doc comment for Optional
1 parent 7000997 commit 5c729f5

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

src/Data/Codec/Argonaut/Record.purs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,10 @@ import Data.Symbol (class IsSymbol)
66
import Prim.Row as R
77
import Prim.RowList as RL
88
import Record as Rec
9-
import Type.Equality as TE
9+
import Safe.Coerce (coerce)
1010
import Type.Proxy (Proxy(..))
1111
import Unsafe.Coerce (unsafeCoerce)
1212

13-
data Optional a = Optional (CA.JsonCodec a)
14-
15-
unOptional a. Optional a CA.JsonCodec a
16-
unOptional (Optional codec) = codec
17-
1813
-- | Constructs a `JsonCodec` for a `Record` from a name and a record of codecs.
1914
-- | The name is used in the error message produced when decoding fails.
2015
-- |
@@ -44,6 +39,19 @@ record
4439
CA.JPropCodec (Record ro)
4540
record = rowListCodec (Proxy Proxy rl)
4641

42+
-- | Used to wrap codec values provided in `record` to indicate the field is optional.
43+
-- |
44+
-- | This will only decode the property as `Nothing` if the field does not exist
45+
-- | in the object - having a values such as `null` assigned will need handling
46+
-- | separately.
47+
-- |
48+
-- | The property will be omitted when encoding and the value is `Nothing`.
49+
newtype Optional a = Optional (CA.JsonCodec a)
50+
51+
-- | A lowercase alias for `Optional`, provided for stylistic reasons only.
52+
optional a. CA.JsonCodec a Optional a
53+
optional = Optional
54+
4755
-- | The class used to enable the building of `Record` codecs by providing a
4856
-- | record of codecs.
4957
class RowListCodec (rlRL.RowList Type) (riRow Type) (roRow Type) | rl ri ro where
@@ -63,7 +71,7 @@ instance rowListCodecConsOptional ∷
6371
CA.recordPropOptional (Proxy Proxy sym) codec tail
6472
where
6573
codec CA.JsonCodec a
66-
codec = TE.from (unOptional (Rec.get (Proxy Proxy sym) codecs))
74+
codec = coerce (Rec.get (Proxy Proxy sym) codecs Optional a)
6775

6876
tail CA.JPropCodec (Record ro')
6977
tail = rowListCodec (Proxy Proxy rs) ((unsafeCoerce Record ri Record ri') codecs)
@@ -79,7 +87,7 @@ else instance rowListCodecCons ∷
7987
CA.recordProp (Proxy Proxy sym) codec tail
8088
where
8189
codec CA.JsonCodec a
82-
codec = TE.from (Rec.get (Proxy Proxy sym) codecs)
90+
codec = Rec.get (Proxy Proxy sym) codecs
8391

8492
tail CA.JPropCodec (Record ro')
8593
tail = rowListCodec (Proxy Proxy rs) ((unsafeCoerce Record ri Record ri') codecs)

test/Test/Record.purs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ innerCodec =
6161
CA.object "Inner" $ CAR.record
6262
{ n: CA.int
6363
, m: CA.boolean
64-
, o: CAR.Optional CA.boolean
64+
, o: CAR.optional CA.boolean
6565
}
6666

6767
genOuter Gen OuterR

0 commit comments

Comments
 (0)