Compare commits

..

17 Commits

Author SHA1 Message Date
Mathew Polzin f8545128cf beginning again to add property wrappers but only to realize property wrapper composition did not land in Swift 5.1 I'll put this on hold again for now. 2019-10-01 00:32:30 -07:00
Mathew Polzin c26d6d99c0 Update README.md 2019-09-29 17:21:43 -07:00
Mathew Polzin 43dcc4fb12 Update README.md 2019-09-29 17:21:08 -07:00
Mathew Polzin abae975f59 Update README.md 2019-09-29 17:20:42 -07:00
Mathew Polzin 0e6b2a7771 Update README.md 2019-09-29 17:14:25 -07:00
Mathew Polzin 194a58ae56 Merge pull request #37 from mattpolzin/feature/basic-error
Feature/basic error
2019-09-29 17:01:25 -07:00
Mathew Polzin f1d6b22f61 Add playground example, add/update documentation, correct visibility of new error payload properties to public. 2019-09-29 16:49:38 -07:00
Mathew Polzin 3057992348 bump podspec version, update Playground examples 2019-09-29 15:57:54 -07:00
Mathew Polzin d4806ff557 Add a few decode examples 2019-09-29 15:36:16 -07:00
Mathew Polzin b0801f7cee Add tests for BasicJSONAPIError and tweak documentation 2019-09-29 15:20:08 -07:00
Mathew Polzin 88c5d400aa Add generic and basic error types. add tests for generic type. 2019-09-29 14:56:04 -07:00
Mathew Polzin 6cd5aeaba6 Update README.md
Update max number of `Include` types in documentation.
2019-09-16 17:16:42 -07:00
Mathew Polzin 7e28cd2606 Merge pull request #35 from mattpolzin/add-include-10
Add include10 Type
2019-09-16 17:13:49 -07:00
Mathew Polzin cf6fa39548 bump Podspec version 2019-09-16 09:58:57 -07:00
Mathew Polzin a24f15dc4e regenerate linuxmain 2019-09-16 09:38:36 -07:00
Mathew Polzin 87e9ee0606 remove tests that are duplicates of those in the Poly package. I just never deleted this file when the Poly stuff moved into its own package. Add support for Include10. 2019-09-16 09:37:34 -07:00
Mathew Polzin 5ed45078a1 Update README.md
Fix incorrect Swift version requirement and suggested SPM dependency version.
2019-09-14 16:44:46 -07:00
25 changed files with 907 additions and 753 deletions
@@ -37,7 +37,7 @@ typealias ToManyRelationship<Entity: Relatable> = JSONAPI.ToManyRelationship<Ent
// JSON:API Documents for this particular API to have Metadata, Links,
// useful Errors, or an APIDescription (The *SPEC* calls this
// "API Description" the "JSON:API Object").
typealias Document<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, UnknownJSONAPIError>
typealias Document<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
// MARK: Entity Definitions
@@ -35,7 +35,7 @@ typealias ThingWithProperties = JSONAPI.ResourceObject<ThingWithPropertiesDescri
//
// NOTE: Using `JSONAPI.EncodableResourceBody` which means the document type will be `Encodable` but not `Decodable`.
//
typealias Document<PrimaryResourceBody: JSONAPI.EncodableResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, UnknownJSONAPIError>
typealias Document<PrimaryResourceBody: JSONAPI.EncodableResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
//
// NOTE: Using `JSONAPI.EncodablePrimaryResource` which means the `ResourceBody` will be `Encodable` but not `Decodable.
@@ -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<SingleResourceBody<AlternativeDog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError>
typealias AltSingleDogDocument = JSONAPI.Document<SingleResourceBody<AlternativeDog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
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<T: JSONAPIDocument>(document: T) {
guard case let .data(body) = document.body else {
return
@@ -71,3 +71,29 @@ func process<T: JSONAPIDocument>(document: T) {
let x: T.Body.Data = body
}
process(document: peopleResponse)
// MARK: - Work with errors
typealias ErrorDoc = JSONAPI.Document<NoResourceBody, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
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)")
}
+2 -2
View File
@@ -139,6 +139,6 @@ public enum HouseDescription: ResourceObjectDescription {
public typealias House = ExampleEntity<HouseDescription>
public typealias SingleDogDocument = JSONAPI.Document<SingleResourceBody<Dog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError>
public typealias SingleDogDocument = JSONAPI.Document<SingleResourceBody<Dog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
public typealias BatchPeopleDocument = JSONAPI.Document<ManyResourceBody<Person>, NoMetadata, NoLinks, Include2<Dog, House>, NoAPIDescription, UnknownJSONAPIError>
public typealias BatchPeopleDocument = JSONAPI.Document<ManyResourceBody<Person>, NoMetadata, NoLinks, Include2<Dog, House>, NoAPIDescription, BasicJSONAPIError<String>>
+2 -2
View File
@@ -16,7 +16,7 @@ Pod::Spec.new do |spec|
#
spec.name = "MP-JSONAPI"
spec.version = "2.0.0"
spec.version = "2.2.0"
spec.summary = "Swift Codable JSON API framework."
# This description is used to generate tags and improve search results.
@@ -136,6 +136,6 @@ See the JSON API Spec here: https://jsonapi.org/format/
# spec.requires_arc = true
# spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
spec.dependency "Poly", "~> 2.0"
spec.dependency "Poly", "~> 2.1"
end
+2 -2
View File
@@ -6,8 +6,8 @@
"repositoryURL": "https://github.com/mattpolzin/Poly.git",
"state": {
"branch": null,
"revision": "38051821d7ef49e590e26e819a2fe447e50be9ff",
"version": "2.0.1"
"revision": "4a08517b24f8e9f6dd8c02ec7da316aac5c00e2e",
"version": "2.1.0"
}
}
]
+1 -1
View File
@@ -18,7 +18,7 @@ let package = Package(
targets: ["JSONAPITesting"])
],
dependencies: [
.package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.0.0")),
.package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.1.0")),
],
targets: [
.target(
+59 -18
View File
@@ -5,15 +5,17 @@ A Swift package for encoding to- and decoding from **JSON API** compliant reques
See the JSON API Spec here: https://jsonapi.org/format/
:warning: This library provides well-tested type safety when working with JSON:API 1.0. However, the Swift compiler can sometimes have difficulty tracking down small typos when initializing `ResourceObjects`. Once the code is written correctly, it will compile, but tracking down the source of programmer errors can be an annoyance. This is mostly a concern when creating resource objects in-code (servers and test cases must do this). Writing a client that uses this framework to ingest JSON API Compliant API responses is much less painful. :warning:
:warning: This library provides well-tested type safety when working with JSON:API 1.0. However, the Swift compiler can sometimes have difficulty tracking down small typos when initializing `ResourceObjects`. Once the code is written correctly, it will compile, but tracking down the source of programmer errors can be an annoyance. This is mostly a concern when creating resource objects in-code (servers and test cases must do this). Writing a client that uses this framework to ingest JSON API Compliant API responses is much less painful.
## Quick Start
:warning: The following Google Colab examples have correct code, but there appears to be an bug in the branch of the Swift compiler currently being used by the Google Colab Swift notebooks such that the `JSONAPI` package cannot be pulled in and you cannot run the examples in-browser.
### Clientside
- [Basic Example](https://colab.research.google.com/drive/1IS7lRSBGoiW02Vd1nN_rfdDbZvTDj6Te)
- [Compound Example](https://colab.research.google.com/drive/1BdF0Kc7l2ixDfBZEL16FY6palweDszQU)
- [Metadata Example](https://colab.research.google.com/drive/10dEESwiE9I3YoyfzVeOVwOKUTEgLT3qr)
- [Errors Example](https://colab.research.google.com/drive/1TIv6STzlHrkTf_-9Eu8sv8NoaxhZcFZH)
- [Basic Example](https://colab.research.google.com/drive/1IS7lRSBGoiW02Vd1nN_rfdDbZvTDj6Te)
- [Compound Example](https://colab.research.google.com/drive/1BdF0Kc7l2ixDfBZEL16FY6palweDszQU)
- [Metadata Example](https://colab.research.google.com/drive/10dEESwiE9I3YoyfzVeOVwOKUTEgLT3qr)
- [Custom Errors Example](https://colab.research.google.com/drive/1TIv6STzlHrkTf_-9Eu8sv8NoaxhZcFZH)
### Serverside
- [GET Example](https://colab.research.google.com/drive/1krbhzSfz8mwkBTQQnKUZJLEtYsJKSfYX)
@@ -23,10 +25,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
<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 -->
- [JSONAPI](#jsonapi)
- [Table of Contents](#table-of-contents)
- [Primary Goals](#primary-goals)
- [Caveat](#caveat)
- [Dev Environment](#dev-environment)
@@ -67,6 +67,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 +88,6 @@ This library works well when used by both the server responsible for serializati
- [JSONAPI+Arbitrary](#jsonapiarbitrary)
- [JSONAPI+OpenAPI](#jsonapiopenapi)
<!-- /TOC -->
## Primary Goals
The primary goals of this framework are:
@@ -102,13 +103,13 @@ If you find something wrong with this library and it isn't already mentioned und
## Dev Environment
### Prerequisites
1. Swift 4.2+
1. Swift 5.1+
2. Swift Package Manager *OR* Cocoapods
### Swift Package Manager
Just include the following in your package's dependencies and add `JSONAPI` to the dependencies for any of your targets.
```
.package(url: "https://github.com/mattpolzin/JSONAPI.git", .upToNextMajor(from: "1.0.0"))
.package(url: "https://github.com/mattpolzin/JSONAPI.git", .upToNextMajor(from: "2.2.0"))
```
### CocoaPods
@@ -122,6 +123,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 +333,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 +406,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<SingleResourceBody<Person>, NoMetadata, NoLinks, NoIncludes, UnknownJSONAPIError>.self
let responseStructure = JSONAPI.Document<SingleResourceBody<Person>, NoMetadata, NoLinks, NoIncludes, BasicJSONAPIError<String>>.self
let document = try decoder.decode(responseStructure, from: data)
```
@@ -452,7 +455,7 @@ The third generic type of a `JSONAPIDocument` is a `Links` struct. `Links` are d
#### `IncludeType`
The fourth generic type of a `JSONAPIDocument` is an `Include`. This type controls which types of `ResourceObject` are looked for when decoding the "included" part of the JSON API document. If you do not expect any included resource objects to be in the document, `NoIncludes` is the way to go. The `JSONAPI` framework provides `Include`s for up to six types of included resource objects. These are named `Include1`, `Include2`, `Include3`, and so on.
The fourth generic type of a `JSONAPIDocument` is an `Include`. This type controls which types of `ResourceObject` are looked for when decoding the "included" part of the JSON API document. If you do not expect any included resource objects to be in the document, `NoIncludes` is the way to go. The `JSONAPI` framework provides `Include`s for up to 10 types of included resource objects. These are named `Include1`, `Include2`, `Include3`, and so on.
**IMPORTANT**: The number trailing "Include" in these type names does not indicate a number of included resource objects, it indicates a number of _types_ of included resource objects. `Include1` can be used to decode any number of included resource objects as long as all the resource objects are of the same _type_.
@@ -470,7 +473,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<Int>`. 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<Either<Int, String>>`.
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<NoResourceBody, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
```
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<YourType>` as the error type for a `Document`.
### `JSONAPI.Meta`
@@ -520,12 +561,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<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, UnknownJSONAPIError>
typealias Document<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
```
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<PrimaryResourceBody: JSONAPI.EncodableResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, UnknownJSONAPIError>
typealias SparseDocument<PrimaryResourceBody: JSONAPI.EncodableResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
```
### Custom Attribute or Relationship Key Mapping
@@ -713,7 +754,7 @@ typealias ToManyRelationship<Entity: Relatable> = JSONAPI.ToManyRelationship<Ent
// JSON:API Documents for this particular API to have Metadata, Links,
// useful Errors, or an APIDescription (The *SPEC* calls this
// "API Description" the "JSON:API Object").
typealias Document<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, UnknownJSONAPIError>
typealias Document<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
// MARK: Entity Definitions
+8
View File
@@ -161,3 +161,11 @@ extension Includes where I: _Poly9 {
return values.compactMap { $0.i }
}
}
// MARK: - 10 includes
public typealias Include10 = Poly10
extension Includes where I: _Poly10 {
public subscript(_ lookup: I.J.Type) -> [I.J] {
return values.compactMap { $0.j }
}
}
@@ -0,0 +1,96 @@
//
// BasicError.swift
// JSONAPI
//
// Created by Mathew Polzin on 9/29/19.
//
/// Most of the JSON:API Spec defined Error fields.
public struct BasicJSONAPIErrorPayload<IdType: Codable & Equatable>: Codable, Equatable, ErrorDictType {
/// a unique identifier for this particular occurrence of the problem
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
public let status: String?
/// an application-specific error code
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
public let title: String?
/// a human-readable explanation specific to this occurrence of the problem. Like `title`, this field’s value can be localized
public let detail: String?
/// an object containing references to the source of the error
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].
public let pointer: String?
/// which URI query parameter caused the error
public let parameter: String?
public init(pointer: String? = nil,
parameter: String? = nil) {
self.pointer = pointer
self.parameter = parameter
}
}
public var definedFields: [String: String] {
let keysAndValues = [
id.map { ("id", String(describing: $0)) },
status.map { ("status", $0) },
code.map { ("code", $0) },
title.map { ("title", $0) },
detail.map { ("detail", $0) },
source.flatMap { $0.pointer.map { ("pointer", $0) } },
source.flatMap { $0.parameter.map { ("parameter", $0) } }
].compactMap { $0 }
return Dictionary(uniqueKeysWithValues: keysAndValues)
}
}
/// `BasicJSONAPIError` optionally decodes many possible fields
/// specified by the JSON:API 1.0 Spec. It gives no type-guarantees of what
/// will be non-nil, but could provide good diagnostic information when
/// you do not know what error structure to expect.
///
/// ```
/// Fields:
/// - id
/// - status
/// - code
/// - title
/// - detail
/// - source
/// - pointer
/// - parameter
/// ```
///
/// The JSON:API Spec does not dictate the type of this particular Id field,
/// so you must specify whether to expect, for example, an `Int` or a `String`
/// in the id field.
///
/// Something like `AnyCodable` from *Flight-School* could be
/// a good option if you do not know what to expect. You could also use
/// `Either<Int, String>` (provided by the `Poly` package that is
/// already a dependency of `JSONAPI`).
///
/// - Important: The `definedFields` property will include fields
/// with non-nil values in a flattened way. There will be no `source` key
/// but there will be `pointer` and `parameter` keys (if those values
/// are non-nil).
public typealias BasicJSONAPIError<IdType: Codable & Equatable> = GenericJSONAPIError<BasicJSONAPIErrorPayload<IdType>>
@@ -0,0 +1,65 @@
//
// GenericError.swift
// JSONAPI
//
// Created by Mathew Polzin on 9/29/19.
//
/// `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`.
public enum GenericJSONAPIError<ErrorPayload: Codable & Equatable>: JSONAPIError {
case unknownError
case error(ErrorPayload)
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = .error(try container.decode(ErrorPayload.self))
} catch {
self = .unknown
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .error(let payload):
try container.encode(payload)
case .unknownError:
try container.encode("unknown")
}
}
public static var unknown: Self {
return .unknownError
}
}
public extension GenericJSONAPIError {
var payload: ErrorPayload? {
switch self {
case .unknownError:
return nil
case .error(let payload):
return payload
}
}
}
public protocol ErrorDictType {
var definedFields: [String: String] { get }
}
extension GenericJSONAPIError: ErrorDictType where ErrorPayload: ErrorDictType {
/// Get a dictionary of all defined fields and their values.
public var definedFields: [String: String] {
switch self {
case .unknownError:
return [:]
case .error(let basicPayload):
return basicPayload.definedFields
}
}
}
@@ -11,7 +11,10 @@ public protocol JSONAPIError: Swift.Error, Equatable, Codable {
/// `UnknownJSONAPIError` can actually be used in any sitaution
/// where you don't know what errors are possible _or_ you just don't
/// care what errors might show up.
/// care what errors might show up. If you don't know how the error
/// will be structured but you would like to have access to more
/// information the server might be providing in the error payload,
/// use `BasicJSONAPIError` instead.
public enum UnknownJSONAPIError: JSONAPIError {
case unknownError
@@ -24,7 +27,7 @@ public enum UnknownJSONAPIError: JSONAPIError {
try container.encode("unknown")
}
public static var unknown: UnknownJSONAPIError {
public static var unknown: Self {
return .unknownError
}
}
@@ -0,0 +1,141 @@
//
// TransformedAttribute.swift
//
// Created by Mathew Polzin on 9/30/19.
//
public protocol AttrType {
associatedtype SerializedType
}
@propertyWrapper
public struct Attr<Serializer, Deserializer, Value>: AttrType where Serializer: Transformer, Deserializer: Transformer, Serializer.From == Value, Deserializer.To == Value {
public typealias SerializedType = Value
private var _wrappedValue: Value?
public var wrappedValue: Value {
guard let ret = _wrappedValue else {
fatalError("Accessed Transformed Value prior to initializing or decoding it.")
}
return ret
}
public init(wrappedValue: Value) {
_wrappedValue = wrappedValue
}
public init(wrappedValue: Value, serializer: Serializer.Type, deserializer: Deserializer.Type) {
_wrappedValue = wrappedValue
}
public init(serializer: Serializer.Type, deserializer: Deserializer.Type) {
_wrappedValue = nil
}
}
extension Attr where
Serializer == IdentityTransformer<Value>,
Deserializer == IdentityTransformer<Value> {
public init(wrappedValue: Value) {
_wrappedValue = wrappedValue
}
public init() {
_wrappedValue = nil
}
}
extension Attr where
Deserializer == IdentityTransformer<Value>,
Serializer: Transformer, Serializer.From == Value {
public init(wrappedValue: Value, serializer: Serializer.Type) {
_wrappedValue = wrappedValue
}
public init(serializer: Serializer.Type) {
_wrappedValue = nil
}
}
extension Attr where
Serializer == IdentityTransformer<Value>,
Deserializer: Transformer, Deserializer.To == Value {
public init(wrappedValue: Value, deserializer: Deserializer.Type) {
_wrappedValue = wrappedValue
}
public init(deserializer: Deserializer.Type) {
_wrappedValue = nil
}
}
extension Attr: Encodable where
Serializer: Transformer, Serializer.To: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Serializer.transform(wrappedValue))
}
}
extension Attr: Decodable where
Deserializer: Transformer, Deserializer.From: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let anyNil: Any? = nil
if container.decodeNil(),
let val = anyNil as? Value {
_wrappedValue = val
} else {
_wrappedValue = try Deserializer.transform(container.decode(Deserializer.From.self))
}
}
}
public protocol _Omittable {
static var nilValue: Self { get }
}
@propertyWrapper
public struct Omittable<T>: AttrType, _Omittable {
public typealias SerializedType = T?
public let wrappedValue: T?
public init(wrappedValue: T?) {
self.wrappedValue = wrappedValue
}
public static var nilValue: Omittable<T> { return .init(wrappedValue: nil) }
}
extension Omittable: Encodable where T: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if Optional(wrappedValue) != nil {
try container.encode(wrappedValue)
}
}
}
extension Omittable: Decodable where T: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self = .init(wrappedValue: try container.decode(T.self))
}
}
extension KeyedDecodingContainer {
public func decode<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T where T : Decodable, T: _Omittable {
return try decodeIfPresent(T.self, forKey: key) ?? T.nilValue
}
}
@@ -29,6 +29,12 @@ public enum IdentityTransformer<T>: ReversibleTransformer {
public static func reverse(_ value: T) throws -> T { return value }
}
extension Optional: Transformer where Wrapped: Transformer {
public static func transform(_ value: Wrapped.From?) throws -> Wrapped.To? {
return try value.map { try Wrapped.transform($0) }
}
}
// MARK: - Validator
/// A Validator is a Transformer that throws an error if an invalid value
@@ -74,3 +74,8 @@ extension Poly8: PrimaryResource, OptionalPrimaryResource where A: PolyWrapped,
extension Poly9: EncodablePrimaryResource, OptionalEncodablePrimaryResource where A: EncodablePolyWrapped, B: EncodablePolyWrapped, C: EncodablePolyWrapped, D: EncodablePolyWrapped, E: EncodablePolyWrapped, F: EncodablePolyWrapped, G: EncodablePolyWrapped, H: EncodablePolyWrapped, I: EncodablePolyWrapped {}
extension Poly9: PrimaryResource, OptionalPrimaryResource where A: PolyWrapped, B: PolyWrapped, C: PolyWrapped, D: PolyWrapped, E: PolyWrapped, F: PolyWrapped, G: PolyWrapped, H: PolyWrapped, I: PolyWrapped {}
// MARK: - 10 types
extension Poly10: EncodablePrimaryResource, OptionalEncodablePrimaryResource where A: EncodablePolyWrapped, B: EncodablePolyWrapped, C: EncodablePolyWrapped, D: EncodablePolyWrapped, E: EncodablePolyWrapped, F: EncodablePolyWrapped, G: EncodablePolyWrapped, H: EncodablePolyWrapped, I: EncodablePolyWrapped, J: EncodablePolyWrapped {}
extension Poly10: PrimaryResource, OptionalPrimaryResource where A: PolyWrapped, B: PolyWrapped, C: PolyWrapped, D: PolyWrapped, E: PolyWrapped, F: PolyWrapped, G: PolyWrapped, H: PolyWrapped, I: PolyWrapped, J: PolyWrapped {}
@@ -9,7 +9,74 @@ import XCTest
import JSONAPI
import JSONAPITesting
struct T1: Encodable {
@Attr(serializer: IntToString.self)
var x: Int
init(x: Int) {
self._x = .init(wrappedValue: x)
}
}
struct T2: Decodable {
@Attr(deserializer: IntToString.self)
var y: String
}
struct Tmp {
@Attr(serializer: IntToString.self)
var x: Int = 5
@Attr(deserializer: IntToString.self)
var y: String = "2"
}
struct T3: Codable {
@Attr(serializer: StringToInt.self, deserializer: IntToString.self)
var y: String = "1"
}
struct T4: Encodable {
@Attr(serializer: StringToInt?.self)
var w: String?
}
struct T5: Codable {
@Attr(serializer: StringToInt?.self, deserializer: IntToString?.self)
var x: String?
}
struct T6: Decodable {
@Omittable
@Attr(deserializer: IntToString?.self)
var y: String?
}
class TransformerTests: XCTestCase {
func test_tmp() {
let t1 = T1(x: 2)
print(encodable: t1)
let t3 = T3(y: "3")
print(encodable: t3)
let t2 = decoded(type: T2.self, data: #"{"y":63}"#.data(using: .utf8)!)
print(t2.y)
let t4 = T4(w: .init(wrappedValue: nil))
let t4_2 = T4(w: .init(wrappedValue: "12"))
print(encodable: t4)
print(encodable: t4_2)
let t5 = decoded(type: T5.self, data: #"{"x":null}"#.data(using: .utf8)!)
let t5_2 = decoded(type: T5.self, data: #"{"x":10}"#.data(using: .utf8)!)
XCTAssertThrowsError(try JSONDecoder().decode(T5.self, from: #"{}"#.data(using: .utf8)!))
print(t5.x)
print(t5_2.x)
let t6 = decoded(type: T6.self, data: #"{}"#.data(using: .utf8)!)
}
func testIdentityTransform() {
let inString = "hello world"
@@ -49,3 +116,23 @@ enum MoreThanFiveCharValidator: Validator {
case fewerThanFiveChars
}
}
enum StringToInt: Transformer {
public static func transform(_ value: String) throws -> Int {
let res = Int(value)
guard let ret = res else {
throw Error.nonIntegerString
}
return ret
}
enum Error: Swift.Error {
case nonIntegerString
}
}
enum IntToString: Transformer {
public static func transform(_ value: Int) throws -> String {
return String(value)
}
}
@@ -0,0 +1,131 @@
//
// BasicJSONAPIErrorTests.swift
// JSONAPITests
//
// Created by Mathew Polzin on 9/29/19.
//
import Foundation
import JSONAPI
import XCTest
import Poly
final class BasicJSONAPIErrorTests: XCTestCase {
func test_initAndEquality() {
let unknown1 = BasicJSONAPIError<String>.unknown
let unknown2 = BasicJSONAPIError<String>.unknownError
XCTAssertEqual(unknown1, unknown2)
let unknown3 = BasicJSONAPIError<Int>.unknownError
XCTAssertEqual(unknown3, .unknown)
let _ = BasicJSONAPIError<Int>.error(.init(id: nil,
status: nil,
code: nil,
title: nil,
detail: nil,
source: nil))
let _ = BasicJSONAPIError<String>.error(.init(id: nil,
status: nil,
code: nil,
title: nil,
detail: nil,
source: nil))
let intError = BasicJSONAPIError<Int>.error(.init(id: 2,
status: nil,
code: nil,
title: nil,
detail: nil,
source: nil))
XCTAssertEqual(intError.payload?.id, 2)
XCTAssertNotEqual(intError, unknown3)
let stringError = BasicJSONAPIError<String>.error(.init(id: "hello",
status: nil,
code: nil,
title: nil,
detail: nil,
source: nil))
XCTAssertEqual(stringError.payload?.id, "hello")
XCTAssertNotEqual(stringError, unknown1)
let wellPopulatedError = BasicJSONAPIError<Int>.error(.init(id: 10,
status: "404",
code: "12",
title: "Missing",
detail: "Resource was not found",
source: .init(pointer: "/data/attributes/id", parameter: "id")))
XCTAssertEqual(wellPopulatedError.payload?.id, 10)
XCTAssertEqual(wellPopulatedError.payload?.status, "404")
XCTAssertEqual(wellPopulatedError.payload?.code, "12")
XCTAssertEqual(wellPopulatedError.payload?.title, "Missing")
XCTAssertEqual(wellPopulatedError.payload?.detail, "Resource was not found")
XCTAssertEqual(wellPopulatedError.payload?.source?.pointer, "/data/attributes/id")
XCTAssertEqual(wellPopulatedError.payload?.source?.parameter, "id")
XCTAssertNotEqual(wellPopulatedError, intError)
}
func test_definedFields() {
let unpopulatedError = BasicJSONAPIError<Int>.error(.init(id: nil,
status: nil,
code: nil,
title: nil,
detail: nil,
source: nil))
XCTAssertEqual(unpopulatedError.definedFields.count, 0)
let wellPopulatedError = BasicJSONAPIError<Int>.error(.init(id: 10,
status: "404",
code: "12",
title: "Missing",
detail: "Resource was not found",
source: .init(pointer: "/data/attributes/id", parameter: "id")))
XCTAssertEqual(wellPopulatedError.definedFields.count, 7)
XCTAssertEqual(wellPopulatedError.definedFields["id"], "10")
XCTAssertEqual(wellPopulatedError.definedFields["status"], "404")
XCTAssertEqual(wellPopulatedError.definedFields["code"], "12")
XCTAssertEqual(wellPopulatedError.definedFields["title"], "Missing")
XCTAssertEqual(wellPopulatedError.definedFields["detail"], "Resource was not found")
XCTAssertEqual(wellPopulatedError.definedFields["pointer"], "/data/attributes/id")
XCTAssertEqual(wellPopulatedError.definedFields["parameter"], "id")
}
func test_decodeAFewExamples() {
let datas = [
"""
{
"id": "hello"
}
""",
"""
{
"id": 1234
}
""",
"""
{
"status": "404",
"title": "Missing",
"links": {
"about": "https://google.com"
}
}
""",
"""
{
"status": 404
}
"""
].map { $0.data(using: .utf8)! }
let errors = datas
.map { decoded(type: BasicJSONAPIError<Either<Int, String>>.self, data: $0) }
XCTAssertEqual(errors[0].payload?.id, .init("hello"))
XCTAssertEqual(errors[1].payload?.id, .init(1234))
XCTAssertEqual(errors[2].payload?.status, "404")
XCTAssertEqual(errors[2].payload?.title, "Missing")
XCTAssertEqual(errors[3], .unknown)
}
}
@@ -0,0 +1,147 @@
//
// GenericJSONAPIErrorTests.swift
// JSONAPITests
//
// Created by Mathew Polzin on 9/29/19.
//
import Foundation
import JSONAPI
import XCTest
final class GenericJSONAPIErrorTests: XCTestCase {
func test_initAndEquality() {
let unknown1 = TestGenericJSONAPIError.unknown
let unknown2 = TestGenericJSONAPIError.unknownError
XCTAssertEqual(unknown1, unknown2)
let known1 = TestGenericJSONAPIError.error(.init(hello: "there", world: 3))
let known2 = TestGenericJSONAPIError.error(.init(hello: "there", world: nil))
XCTAssertNotEqual(unknown1, known1)
XCTAssertNotEqual(unknown1, known2)
XCTAssertNotEqual(known1, known2)
}
func test_decodeKnown() {
let datas = [
"""
{
"hello": "world"
}
""",
"""
{
"hello": "there",
"world": 2
}
""",
"""
{
"hello": "three",
"world": null
}
"""
].map { $0.data(using: .utf8)! }
let errors = datas
.map { decoded(type: TestGenericJSONAPIError.self, data: $0) }
XCTAssertEqual(errors[0], .error(TestPayload(hello: "world", world: nil)))
XCTAssertEqual(errors[1], .error(TestPayload(hello: "there", world: 2)))
XCTAssertEqual(errors[2], .error(TestPayload(hello: "three", world: nil)))
}
func test_decodeUnknown() {
let data =
"""
{
"world": 2
}
""".data(using: .utf8)!
let error = decoded(type: TestGenericJSONAPIError.self, data: data)
XCTAssertEqual(error, .unknown)
}
func test_encode() {
let datas = [
"""
{
"hello": "world"
}
""",
"""
{
"hello": "there",
"world": 2
}
""",
"""
{
"hello": "three",
"world": null
}
"""
].map { $0.data(using: .utf8)! }
datas.forEach { data in
test_DecodeEncodeEquality(type: TestGenericJSONAPIError.self, data: data)
}
}
func test_encodeUnknown() {
let error = TestGenericJSONAPIError.unknownError
let encodedError = encoded(value: ["errors": [error]])
XCTAssertEqual(String(data: encodedError, encoding: .utf8)!, #"{"errors":["unknown"]}"#)
}
func test_payloadAccess() {
let error1 = TestGenericJSONAPIError.error(.init(hello: "world", world: 3))
let error2 = TestGenericJSONAPIError.error(.init(hello: "there", world: nil))
let error3 = TestGenericJSONAPIError.unknown
XCTAssertEqual(error1.payload?.hello, "world")
XCTAssertEqual(error1.payload?.world, 3)
XCTAssertEqual(error2.payload?.hello, "there")
XCTAssertNil(error2.payload?.world)
XCTAssertNil(error3.payload?.hello)
XCTAssertNil(error3.payload?.world)
}
func test_definedFields() {
let error1 = TestGenericJSONAPIError.error(.init(hello: "world", world: 3))
let error2 = TestGenericJSONAPIError.error(.init(hello: "there", world: nil))
let error3 = TestGenericJSONAPIError.unknown
XCTAssertEqual(error1.definedFields.count, 2)
XCTAssertEqual(error2.definedFields.count, 1)
XCTAssertEqual(error3.definedFields.count, 0)
XCTAssertEqual(error1.definedFields["hello"], "world")
XCTAssertEqual(error1.definedFields["world"], "3")
XCTAssertEqual(error2.definedFields["hello"], "there")
XCTAssertNil(error2.definedFields["world"])
XCTAssertNil(error3.definedFields["hello"])
XCTAssertNil(error3.definedFields["world"])
}
}
private struct TestPayload: Codable, Equatable, ErrorDictType {
let hello: String
let world: Int?
public var definedFields: [String : String] {
let keysAndValues = [
("hello", hello),
world.map { ("world", String($0)) }
].compactMap { $0 }
return Dictionary(uniqueKeysWithValues: keysAndValues)
}
}
private typealias TestGenericJSONAPIError = GenericJSONAPIError<TestPayload>

Some files were not shown because too many files have changed in this diff Show More