Skip to content

Commit

Permalink
Added nested responses
Browse files Browse the repository at this point in the history
  • Loading branch information
Philip Niedertscheider committed Oct 8, 2021
1 parent cef97bb commit 00df1ad
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,33 @@ struct Response: Decodable {

Multiple properties can be declared with this property wrapper. All of them will have the value set.

#### Nested Responses

To support inheritance, which can be especially usefule for pagination, use the property wrapper `@NestedResponse` to add nested responses.

While decoding the flat HTTP response will be applied recursively to all nested responses, therefore it is possible, that different nested responses access different values of the original HTTP response.

**Example:**

```swift
struct PaginatedResponse<NestedRequest: Request>: Decodable {

/// Header which indicates how many more elements are available
@ResponseHeader<DefaultHeaderStrategy> var totalElements

@NestedResponse var nested: NestedRequest
}

struct ListRequest: Request {

typealias Response = PaginatedResponse<ListResponse>

struct ListResponse: Decodable {
// see other examples
}
}
```

### HTTP API Client

The easiest way of sending Postie requests, is using the `HTTPAPIClient` which takes care of encoding requests, and decoding responses.
Expand Down
16 changes: 16 additions & 0 deletions Sources/Postie/Responses/NestedResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
@propertyWrapper
public struct NestedResponse<Response: Decodable> {

public var wrappedValue: Response

public init(wrappedValue: Response) {
self.wrappedValue = wrappedValue
}
}

extension NestedResponse: Decodable {

public init(from decoder: Decoder) throws {
wrappedValue = try Response(from: decoder)
}
}

0 comments on commit 00df1ad

Please sign in to comment.