File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff 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+ ```
You can’t perform that action at this time.
0 commit comments