From f1d6b22f61edc6f09d10e7dda5fa8b7050a17939 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 29 Sep 2019 16:49:38 -0700 Subject: [PATCH] Add playground example, add/update documentation, correct visibility of new error payload properties to public. --- .../Usage.xcplaygroundpage/Contents.swift | 30 +++++++++- README.md | 59 +++++++++++++++---- Sources/JSONAPI/Error/BasicJSONAPIError.swift | 42 +++++++++---- .../JSONAPI/Error/GenericJSONAPIError.swift | 2 - .../Error/BasicJSONAPIErrorTests.swift | 2 +- 5 files changed, 108 insertions(+), 27 deletions(-) diff --git a/JSONAPI.playground/Pages/Usage.xcplaygroundpage/Contents.swift b/JSONAPI.playground/Pages/Usage.xcplaygroundpage/Contents.swift index a50f24f..e5434e5 100644 --- a/JSONAPI.playground/Pages/Usage.xcplaygroundpage/Contents.swift +++ b/JSONAPI.playground/Pages/Usage.xcplaygroundpage/Contents.swift @@ -24,7 +24,7 @@ let dogOwner: Person.Identifier? = dogFromData.flatMap { $0 ~> \.owner } // MARK: - Parse a request or response body with one Dog in it using an alternative model -typealias AltSingleDogDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> +typealias AltSingleDogDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError> let altDogResponse = try! JSONDecoder().decode(AltSingleDogDocument.self, from: singleDogData) let altDogFromData = altDogResponse.body.primaryResource?.value let altDogHuman: Person.Identifier? = altDogFromData.flatMap { $0 ~> \.human } @@ -63,7 +63,7 @@ if case let .data(bodyData) = peopleResponse.body { // MARK: - Work in the abstract - +print("-----") func process(document: T) { guard case let .data(body) = document.body else { return @@ -71,3 +71,29 @@ func process(document: T) { let x: T.Body.Data = body } process(document: peopleResponse) + +// MARK: - Work with errors +typealias ErrorDoc = JSONAPI.Document> + +let mockErrorData = +""" +{ + "errors": [ + { + "status": "500", + "title": "Internal Server Error", + "detail": "Server fell over while parsing your request." + } + ] +} +""".data(using: .utf8)! + +let errorResponse = try! JSONDecoder().decode(ErrorDoc.self, from: mockErrorData) + +switch errorResponse.body { +case .data: + print("cool, data!") +case .errors(let errors, let meta, let links): + let errorDetails = errors.compactMap { $0.payload?.detail } + print("error details: \(errorDetails)") +} diff --git a/README.md b/README.md index 733e9ca..91a58f8 100644 --- a/README.md +++ b/README.md @@ -23,10 +23,8 @@ See the JSON API Spec here: https://jsonapi.org/format/ This library works well when used by both the server responsible for serialization and the client responsible for deserialization. Check out the [example](#example) further down in this README. ## Table of Contents - - [JSONAPI](#jsonapi) - - [Table of Contents](#table-of-contents) - [Primary Goals](#primary-goals) - [Caveat](#caveat) - [Dev Environment](#dev-environment) @@ -67,6 +65,9 @@ This library works well when used by both the server responsible for serializati - [`IncludeType`](#includetype) - [`APIDescriptionType`](#apidescriptiontype) - [`Error`](#error) + - [`UnknownJSONAPIError`](#unknownjsonapierror) + - [`BasicJSONAPIError`](#basicjsonapierror) + - [`GenericJSONAPIError`](#genericjsonapierror) - [`JSONAPI.Meta`](#jsonapimeta) - [`JSONAPI.Links`](#jsonapilinks) - [`JSONAPI.RawIdType`](#jsonapirawidtype) @@ -85,8 +86,6 @@ This library works well when used by both the server responsible for serializati - [JSONAPI+Arbitrary](#jsonapiarbitrary) - [JSONAPI+OpenAPI](#jsonapiopenapi) - - ## Primary Goals The primary goals of this framework are: @@ -122,6 +121,8 @@ To use this framework in your project via Cocoapods, add the following dependenc To create an Xcode project for JSONAPI, run `swift package generate-xcodeproj` +With Xcode 11+ you can also just open the folder containing your clone of this repository and begin working. + ### Running the Playground To run the included Playground files, create an Xcode project using Swift Package Manager, then create an Xcode Workspace in the root of the repository and add both the generated Xcode project and the playground to the Workspace. @@ -330,7 +331,7 @@ let favoriteColor: String = person.favoriteColor let favoriteColor: String = person[\.favoriteColor] ``` -In both cases you retain type-safety, although neither plays particularly nicely with code autocompletion. It is best practice to pick an attribute access syntax and stick with it. At some point in the future the syntax deemed less desirable may be deprecated. +In both cases you retain type-safety. It is best practice to pick an attribute access syntax and stick with it. At some point in the future the syntax deemed less desirable may be deprecated. #### `Transformer` @@ -403,7 +404,7 @@ The entirety of a JSON API request or response is encoded or decoded from- or to ```swift let decoder = JSONDecoder() -let responseStructure = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, UnknownJSONAPIError>.self +let responseStructure = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, BasicJSONAPIError>.self let document = try decoder.decode(responseStructure, from: data) ``` @@ -470,7 +471,45 @@ You can supply any `JSONAPI.Meta` type as the metadata type of the API descripti #### `Error` -The final generic type of a `JSONAPIDocument` is the `Error`. You should create an error type that can decode all the errors you expect your `JSONAPIDocument` to be able to decode. As prescribed by the **SPEC**, these errors will be found in the root document member `errors`. +The final generic type of a `JSONAPIDocument` is the `Error`. + +You can either create an error type that can handle all the errors you expect your `JSONAPIDocument` to be able to encode/decode or use an out-of-box error type described here. As prescribed by the **SPEC**, these errors will be found under the root document key `errors`. + +##### `UnknownJSONAPIError` +The `UnknownJSONAPIError` type will always succeed in parsing errors but it will not give you any information about what error occurred. You will generally get more bang for your buck out of the next error type described. + +##### `BasicJSONAPIError` +The `BasicJSONAPIError` type will always succeed unless it is faced with an `id` field of an unexpected type, although it still "succeeds" in falling back to its `.unknown` case when that happens. This type extracts _most_ of the fields the **SPEC** describes [here](https://jsonapi.org/format/#error-objects). Because all of these fields are optional in the **SPEC**, they are optional on the `BasicJSONAPIError` type. You will have to create your own error type if you want to define certain fields as non-optional or parse metadata or links out of error objects. + +🗒Metadata and links are supported at the Document level for error responses, the are just not supported hanging off of the individual errors in the `errors` array of the response when using this error type. + +The `BasicJSONAPIError` type is generic on one thing: The type it expects for the `id` field. If you expect integer `ids` back, you use `BasicJSONAPIError`. The same can be done for `String` or any other type that is both `Codable` and `Equatable`. You can even employ something like `AnyCodable` from *Flight-School* as your id field type. If you only need to handle a small subset of possible `id` field types, you can also use the `Poly` library that is already a dependency of `JSONAPI`. For example, you might expect a mix of `String` and `Int` ids for some reason: `BasicJSONAPIError>`. + +The two easiest ways to access the available properties of an error response are under the `payload` property of the error (this property is `nil` if the error was parsed as `.unknown`) or by asking the error for its `definedFields` dictionary. + +As an example, let's say you have the following `Document` type that is destined for errors: +```swift +typealias ErrorDoc = JSONAPI.Document> +``` +And you've parsed an error response +```swift +let errorResponse = try! JSONDecoder().decode(ErrorDoc.self, from: mockErrorData) +``` +You can get at the `Document` body and errors in a couple of different ways, but for one you can switch on the body: +```swift +switch errorResponse.body { +case .data: + print("cool, data!") + +case .errors(let errors, let meta, let links): + let errorDetails = errors.compactMap { $0.payload?.detail } + + print("error details: \(errorDetails)") +} +``` + +##### `GenericJSONAPIError` +This type makes it simple to use your own error payload structures as `JSONAPIError` types. Simply define a `Codable` and `Equatable` struct and then use `GenericJSONAPIError` as the error type for a `Document`. ### `JSONAPI.Meta` @@ -520,12 +559,12 @@ There is a sparse fieldsets example included with this repository as a Playgroun #### Sparse Fieldset `typealias` comparisons You might have found a `typealias` like the following for encoding/decoding `JSONAPI.Document`s (note the primary resource body is a `JSONAPI.ResourceBody`): ```swift -typealias Document = JSONAPI.Document +typealias Document = JSONAPI.Document> ``` In order to support sparse fieldsets (which are encode-only), the following companion `typealias` would be useful (note the primary resource body is a `JSONAPI.EncodableResourceBody`): ```swift -typealias SparseDocument = JSONAPI.Document +typealias SparseDocument = JSONAPI.Document> ``` ### Custom Attribute or Relationship Key Mapping @@ -713,7 +752,7 @@ typealias ToManyRelationship = JSONAPI.ToManyRelationship = JSONAPI.Document +typealias Document = JSONAPI.Document> // MARK: Entity Definitions diff --git a/Sources/JSONAPI/Error/BasicJSONAPIError.swift b/Sources/JSONAPI/Error/BasicJSONAPIError.swift index fa0158d..d3859eb 100644 --- a/Sources/JSONAPI/Error/BasicJSONAPIError.swift +++ b/Sources/JSONAPI/Error/BasicJSONAPIError.swift @@ -5,30 +5,48 @@ // Created by Mathew Polzin on 9/29/19. // -import Foundation - /// Most of the JSON:API Spec defined Error fields. public struct BasicJSONAPIErrorPayload: Codable, Equatable, ErrorDictType { /// a unique identifier for this particular occurrence of the problem - let id: IdType? -// let links: Links? // we skip this for now to avoid adding complexity to using this basic type. + public let id: IdType? +// public let links: Links? // we skip this for now to avoid adding complexity to using this basic type. /// the HTTP status code applicable to this problem - let status: String? + public let status: String? /// an application-specific error code - let code: String? + public let code: String? /// a short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization - let title: String? + public let title: String? /// a human-readable explanation specific to this occurrence of the problem. Like `title`, this field’s value can be localized - let detail: String? + public let detail: String? /// an object containing references to the source of the error - let source: Source? -// let meta: Meta? // we skip this for now to avoid adding complexity to using this basic type + public let source: Source? +// public let meta: Meta? // we skip this for now to avoid adding complexity to using this basic type + + public init(id: IdType? = nil, + status: String? = nil, + code: String? = nil, + title: String? = nil, + detail: String? = nil, + source: Source? = nil) { + self.id = id + self.status = status + self.code = code + self.title = title + self.detail = detail + self.source = source + } public struct Source: Codable, Equatable { /// a JSON Pointer [RFC6901] to the associated entity in the request document [e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute]. - let pointer: String? + public let pointer: String? /// which URI query parameter caused the error - let parameter: String? + public let parameter: String? + + public init(pointer: String? = nil, + parameter: String? = nil) { + self.pointer = pointer + self.parameter = parameter + } } public var definedFields: [String: String] { diff --git a/Sources/JSONAPI/Error/GenericJSONAPIError.swift b/Sources/JSONAPI/Error/GenericJSONAPIError.swift index e151311..91ce2b8 100644 --- a/Sources/JSONAPI/Error/GenericJSONAPIError.swift +++ b/Sources/JSONAPI/Error/GenericJSONAPIError.swift @@ -5,8 +5,6 @@ // Created by Mathew Polzin on 9/29/19. // -import Foundation - /// `GenericJSONAPIError` can be used to specify whatever error /// payload you expect to need to parse in responses and handle any /// other payload structure as `.unknownError`. diff --git a/Tests/JSONAPITests/Error/BasicJSONAPIErrorTests.swift b/Tests/JSONAPITests/Error/BasicJSONAPIErrorTests.swift index 05bcf2f..89dc188 100644 --- a/Tests/JSONAPITests/Error/BasicJSONAPIErrorTests.swift +++ b/Tests/JSONAPITests/Error/BasicJSONAPIErrorTests.swift @@ -6,7 +6,7 @@ // import Foundation -@testable import JSONAPI +import JSONAPI import XCTest import Poly