@@ -6,15 +6,10 @@ import Data.Symbol (class IsSymbol)
6
6
import Prim.Row as R
7
7
import Prim.RowList as RL
8
8
import Record as Rec
9
- import Type.Equality as TE
9
+ import Safe.Coerce ( coerce )
10
10
import Type.Proxy (Proxy (..))
11
11
import Unsafe.Coerce (unsafeCoerce )
12
12
13
- data Optional a = Optional (CA.JsonCodec a )
14
-
15
- unOptional ∷ ∀ a . Optional a → CA.JsonCodec a
16
- unOptional (Optional codec) = codec
17
-
18
13
-- | Constructs a `JsonCodec` for a `Record` from a name and a record of codecs.
19
14
-- | The name is used in the error message produced when decoding fails.
20
15
-- |
@@ -44,6 +39,19 @@ record
44
39
→ CA.JPropCodec (Record ro )
45
40
record = rowListCodec (Proxy ∷ Proxy rl )
46
41
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
+
47
55
-- | The class used to enable the building of `Record` codecs by providing a
48
56
-- | record of codecs.
49
57
class RowListCodec (rl ∷ RL.RowList Type ) (ri ∷ Row Type ) (ro ∷ Row Type ) | rl → ri ro where
@@ -63,7 +71,7 @@ instance rowListCodecConsOptional ∷
63
71
CA .recordPropOptional (Proxy ∷ Proxy sym ) codec tail
64
72
where
65
73
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 )
67
75
68
76
tail ∷ CA.JPropCodec (Record ro' )
69
77
tail = rowListCodec (Proxy ∷ Proxy rs ) ((unsafeCoerce ∷ Record ri → Record ri' ) codecs)
@@ -79,7 +87,7 @@ else instance rowListCodecCons ∷
79
87
CA .recordProp (Proxy ∷ Proxy sym ) codec tail
80
88
where
81
89
codec ∷ CA.JsonCodec a
82
- codec = TE .from ( Rec .get (Proxy ∷ Proxy sym ) codecs)
90
+ codec = Rec .get (Proxy ∷ Proxy sym ) codecs
83
91
84
92
tail ∷ CA.JPropCodec (Record ro' )
85
93
tail = rowListCodec (Proxy ∷ Proxy rs ) ((unsafeCoerce ∷ Record ri → Record ri' ) codecs)
0 commit comments