Skip to content

Commit 6574592

Browse files
justinwoopaf31
authored andcommitted
Add reference to howto repo (#19)
* Add reference to howto-foreign-generics repo * add Example Usage section to README
1 parent 1292952 commit 6574592

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,37 @@ Generic deriving for `purescript-foreign`.
66

77
- [Module Documentation](docs/Data/Foreign/Generic.md)
88
- [Example](test/Main.purs)
9+
- [Further examples in this repo](https://github.com/justinwoo/purescript-howto-foreign-generic)
10+
11+
## Example Usage
12+
13+
```purescript
14+
import Data.Foreign.Class (class AsForeign, class IsForeign, readJSON, write)
15+
import Data.Foreign.Generic (defaultOptions, readGeneric, toForeignGeneric)
16+
import Data.Generic.Rep (class Generic)
17+
import Data.Generic.Rep.Show (genericShow)
18+
19+
newtype MyRecord = MyRecord {a :: Int}
20+
21+
derive instance genericMyRecord :: Generic MyRecord _
22+
23+
instance isForeignMyRecord :: IsForeign MyRecord where
24+
read = readGeneric $ defaultOptions {unwrapSingleConstructors = true}
25+
26+
instance asForeignMyRecord :: AsForeign MyRecord where
27+
write = toForeignGeneric $ defaultOptions {unwrapSingleConstructors = true}
28+
29+
toJSONString = write >>> unsafeStringify
30+
fromJSONString = readJSON >>> runExcept
31+
32+
main :: forall e. Eff (console :: CONSOLE | e) Unit
33+
main = do
34+
log $ toJSONString (MyRecord {a: 1})
35+
-- {a: 1}
36+
37+
log $ show eMyRecord
38+
-- Right (MyRecord {a: 1})
39+
where
40+
eMyRecord :: Either _ MyRecord
41+
eMyRecord = fromJSONString """{"a": 1}"""
42+
```

0 commit comments

Comments
 (0)