Skip to content

Commit b1780d6

Browse files
committed
Add example of using SuccessDocument to short circuit errors as decoding failures.
1 parent a604d57 commit b1780d6

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

documentation/usage.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,20 @@ The `Document` type also supplies two nested types that guarantee either a succe
382382

383383
In general, if you want to encode or decode a document you will want the flexibility of representing either success or errors. When you know you will be working with one or the other in a particular context, `Document.SuccessDocument` and `Document.ErrorDocument` will provide additional convenience: they only expose relevant initializers (a success document cannot be initialized with errors), they only succeed to decode given the expected result, and success documents provide non-optional access to the `data` property that is normally optional on the `body`.
384384

385+
For example:
386+
```swift
387+
typealias Response = JSONAPI.Document<...>
388+
389+
let decoder = JSONDecoder()
390+
let document = try decoder.decode(Response.SuccessDocument.self, from: ...)
391+
392+
// the following are non-optional because we know that if the document did not
393+
// contain a `data` body (i.e. if it was an error response) then it would have
394+
// failed to decode above.
395+
let primaryResource = document.primaryResource
396+
let includes = document.includes
397+
```
398+
385399
### `CompoundResource`
386400
`CompoundResource` packages a primary resource with relatives (stored using the same `Include` types that `Document` uses). The `CompoundResource` type can be a convenient way to package a resource and its relatives to be later turned into a `Document`; A single resource body for a document is a straight forward representation of a `CompoundResource`, but `Document` will take an array of `CompoundResources` and create a batch ("many") resource body containing all the primary resources and uniquely including each relative as required by the **SPEC**.
387401

0 commit comments

Comments
 (0)