@@ -24,8 +24,9 @@ module Data.Codec.Argonaut
24
24
, recordProp
25
25
, recordPropOptional
26
26
, fix
27
- , prismaticCodec
27
+ , named
28
28
, coercible
29
+ , prismaticCodec
29
30
, module Exports
30
31
) where
31
32
@@ -35,7 +36,7 @@ import Control.Monad.Reader (ReaderT(..), runReaderT)
35
36
import Control.Monad.Writer (Writer , mapWriter , writer )
36
37
import Data.Argonaut.Core as J
37
38
import Data.Array as A
38
- import Data.Bifunctor (bimap )
39
+ import Data.Bifunctor (bimap , lmap )
39
40
import Data.Bifunctor as BF
40
41
import Data.Codec (BasicCodec , Codec , GCodec (..), basicCodec , bihoistGCodec , decode , encode )
41
42
import Data.Codec (decode , encode , (<~<), (>~>), (~)) as Exports
@@ -373,6 +374,24 @@ fix f =
373
374
(\x → decode (f (fix f)) x)
374
375
(\x → encode (f (fix f)) x)
375
376
377
+ -- | A codec for introducing names into error messages - useful when definiting a codec for a type
378
+ -- | synonym for a record, for instance.
379
+ named ∷ ∀ a . String → JsonCodec a -> JsonCodec a
380
+ named name codec =
381
+ basicCodec
382
+ (lmap (Named name) <<< decode codec)
383
+ (encode codec)
384
+
385
+ -- | A codec for types that can be safely coerced.
386
+ -- |
387
+ -- | Accepts the name of the target type as an argument to improve error messaging when the inner
388
+ -- | codec fails.
389
+ coercible ∷ ∀ a b . Coercible a b ⇒ String → JsonCodec a → JsonCodec b
390
+ coercible name codec =
391
+ basicCodec
392
+ (bimap (Named name) coerce <<< decode codec)
393
+ (coerce (encode codec))
394
+
376
395
-- | Adapts an existing codec with a pair of functions to allow a value to be
377
396
-- | further refined. If the inner decoder fails an `UnexpectedValue` error will
378
397
-- | be raised for JSON input.
@@ -417,13 +436,3 @@ prismaticCodec name f g orig =
417
436
basicCodec
418
437
(\json' → note (Named name (UnexpectedValue json')) <<< f =<< decode orig json')
419
438
(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