Skip to content

Commit b17465f

Browse files
authored
Merge pull request #9 from garyb/prismatic
Add prismatic codec
2 parents b85cca8 + f66f8f3 commit b17465f

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/Data/Codec/Argonaut.purs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ module Data.Codec.Argonaut
2121
, record
2222
, recordProp
2323
, fix
24+
, prismaticCodec
2425
, module Exports
2526
) where
2627

@@ -33,16 +34,16 @@ import Data.Array as A
3334
import Data.Bifunctor as BF
3435
import Data.Codec (BasicCodec, Codec, GCodec(..), basicCodec, bihoistGCodec, decode, encode)
3536
import Data.Codec (decode, encode, (~), (<~<)) as Exports
36-
import Data.Either (Either(..))
37+
import Data.Either (Either(..), note)
3738
import Data.Generic.Rep (class Generic)
3839
import Data.Generic.Rep.Show (genericShow)
3940
import Data.Int as I
4041
import Data.List ((:))
4142
import Data.List as L
4243
import Data.Maybe (Maybe(..), maybe, fromJust)
4344
import Data.Profunctor.Star (Star(..))
44-
import Data.String as S
4545
import Data.StrMap as SM
46+
import Data.String as S
4647
import Data.Symbol (class IsSymbol, SProxy, reflectSymbol)
4748
import Data.Traversable (traverse)
4849
import Data.Tuple (Tuple(..))
@@ -246,3 +247,15 @@ fix f =
246247
basicCodec
247248
(\x → decode (f (fix f)) x)
248249
(\x → encode (f (fix f)) x)
250+
251+
-- | Adapts an existing codec with a pair of functions to allow a value to be
252+
-- | further refined. If the inner decoder fails an `UnexpectedValue` error will
253+
-- | be raised for JSON input.
254+
-- |
255+
-- | This function is named as such as the pair of functions it accepts
256+
-- | correspond with the `preview` and `view` functions of a `Prism`-style lens.
257+
prismaticCodec a b. (a Maybe b) (b a) JsonCodec a JsonCodec b
258+
prismaticCodec f g orig =
259+
basicCodec
260+
(\json → note (UnexpectedValue json) <<< f =<< (decode orig json))
261+
(encode orig <<< g)

0 commit comments

Comments
 (0)