@@ -25,6 +25,7 @@ module Data.Codec.Argonaut
25
25
, recordPropOptional
26
26
, fix
27
27
, prismaticCodec
28
+ , coercible
28
29
, module Exports
29
30
) where
30
31
@@ -34,6 +35,7 @@ import Control.Monad.Reader (ReaderT(..), runReaderT)
34
35
import Control.Monad.Writer (Writer , mapWriter , writer )
35
36
import Data.Argonaut.Core as J
36
37
import Data.Array as A
38
+ import Data.Bifunctor (bimap )
37
39
import Data.Bifunctor as BF
38
40
import Data.Codec (BasicCodec , Codec , GCodec (..), basicCodec , bihoistGCodec , decode , encode )
39
41
import Data.Codec (decode , encode , (<~<), (>~>), (~)) as Exports
@@ -51,7 +53,9 @@ import Data.Traversable (traverse)
51
53
import Data.Tuple (Tuple (..))
52
54
import Foreign.Object as FO
53
55
import Partial.Unsafe (unsafePartial )
56
+ import Prim.Coerce (class Coercible )
54
57
import Prim.Row as Row
58
+ import Safe.Coerce (coerce )
55
59
import Type.Proxy (Proxy )
56
60
import Unsafe.Coerce (unsafeCoerce )
57
61
@@ -413,3 +417,13 @@ prismaticCodec name f g orig =
413
417
basicCodec
414
418
(\json' → note (Named name (UnexpectedValue json')) <<< f =<< decode orig json')
415
419
(encode orig <<< g)
420
+
421
+ -- | A codec for types that can be safely coerced.
422
+ -- |
423
+ -- | Accepts the name of the target type as an argument to improve error messaging when the inner
424
+ -- | codec fails.
425
+ coercible ∷ ∀ a b . Coercible a b ⇒ String → JsonCodec a → JsonCodec b
426
+ coercible name codec =
427
+ basicCodec
428
+ (bimap (Named name) coerce <<< decode codec)
429
+ (coerce (encode codec))
0 commit comments