Skip to content

Commit f8766cb

Browse files
committed
Add note about newtypes
1 parent 9326539 commit f8766cb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,32 @@ The library provides a [`Data.Codec.Argonaut.Common`](https://pursuit.purescript
180180

181181
There is also a [`Data.Codec.Argonaut.Compat`](https://pursuit.purescript.org/packages/purescript-codec-argonaut/docs/Data.Codec.Argonaut.Compat) module provided for codecs that need to preserve compatibility with the encoding using by [`purescript-argonaut-codecs`](https://github.com/purescript-contrib/purescript-argonaut-codecs). These codecs have some issues, like the inability to accurately encode nested `Maybe`s, so if possible, `Common` should be preferred.
182182

183+
### Newtypes
184+
185+
If you have a codec for a `newtype` with a [`Newtype`](https://pursuit.purescript.org/packages/purescript-newtype/docs/Data.Newtype#t:Newtype) instance, you can use the [`wrapIso`](https://pursuit.purescript.org/packages/purescript-profunctor/docs/Data.Profunctor#v:wrapIso) function from [`purescript-profunctor`](https://github.com/purescript/purescript-profunctor) to adapt a codec to work with the `newtype`. For example:
186+
187+
``` purescript
188+
import Data.Codec.Argonaut.Common as CA
189+
import Data.Codec.Argonaut.Record as CAR
190+
import Data.Newtype (class Newtype)
191+
import Data.Profunctor (wrapIso)
192+
193+
type PersonRec = { "Name" ∷ String, age ∷ Int, "is active" ∷ Boolean }
194+
195+
newtype Person = Person PersonRec
196+
197+
derive instance newtypePerson ∷ Newtype Person _
198+
199+
codec ∷ CA.JsonCodec Person
200+
codec =
201+
wrapIso Person
202+
(CAR.object "Person"
203+
{ "Name": CA.string
204+
, age: CA.int
205+
, "is active": CA.boolean
206+
})
207+
```
208+
183209
### "Prismatic" codecs
184210

185211
If you have a type with a pair of functions like the `preview` and `view` that make up a prism (`preview :: a -> Maybe b`, `view :: b -> a`), you can use these to adapt an existing codec to further refine it.

0 commit comments

Comments
 (0)