@@ -24,8 +24,9 @@ module Data.Codec.Argonaut
2424 , recordProp
2525 , recordPropOptional
2626 , fix
27- , prismaticCodec
27+ , named
2828 , coercible
29+ , prismaticCodec
2930 , module Exports
3031 ) where
3132
@@ -35,7 +36,7 @@ import Control.Monad.Reader (ReaderT(..), runReaderT)
3536import Control.Monad.Writer (Writer , mapWriter , writer )
3637import Data.Argonaut.Core as J
3738import Data.Array as A
38- import Data.Bifunctor (bimap )
39+ import Data.Bifunctor (bimap , lmap )
3940import Data.Bifunctor as BF
4041import Data.Codec (BasicCodec , Codec , GCodec (..), basicCodec , bihoistGCodec , decode , encode )
4142import Data.Codec (decode , encode , (<~<), (>~>), (~)) as Exports
@@ -373,6 +374,24 @@ fix f =
373374 (\x → decode (f (fix f)) x)
374375 (\x → encode (f (fix f)) x)
375376
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+
376395-- | Adapts an existing codec with a pair of functions to allow a value to be
377396-- | further refined. If the inner decoder fails an `UnexpectedValue` error will
378397-- | be raised for JSON input.
@@ -417,13 +436,3 @@ prismaticCodec name f g orig =
417436 basicCodec
418437 (\json' → note (Named name (UnexpectedValue json')) <<< f =<< decode orig json')
419438 (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