mirror of
https://github.com/encounter/JSONAPI.git
synced 2026-07-10 12:18:40 -07:00
Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f41521e33b | |||
| 45ec7ba753 | |||
| 6ab4237c97 | |||
| 75711648a4 | |||
| 2b4209ccb1 | |||
| ebd11df104 | |||
| 96da1b4e21 | |||
| c7696d83fa | |||
| 8ee04d8932 | |||
| 4a7a14b1b0 | |||
| a6b7d7a94a | |||
| 1010489a02 | |||
| ae855c85ee | |||
| 440b649577 | |||
| 54551617b4 | |||
| 8c3a82ec23 | |||
| e9a3b35dc7 | |||
| 2eecf95995 | |||
| 4dc30ddc1c | |||
| 455ff64326 | |||
| 0b4baf35d5 | |||
| 11ef050d58 | |||
| 86344ef93f | |||
| 7fabe2574e | |||
| 19636a47f0 | |||
| 0538de48cb | |||
| 024fe2d452 | |||
| 832161628b | |||
| f37f44cfda | |||
| ae7e0f528a | |||
| 9f42e5fa3f | |||
| 3e96adf775 | |||
| 83233a7e1a | |||
| adcc6bfb10 | |||
| 6f9a2df605 | |||
| c24b70b49f | |||
| 7b56e35a91 | |||
| e6f82c6052 | |||
| d6f01d6c1d | |||
| a7f6ed5845 | |||
| 87271b93f9 | |||
| 706346e3a6 | |||
| 33a5ff41a0 | |||
| 0fe5c53ada | |||
| f7bfa91ccc | |||
| 1a15ab6f9d | |||
| eb85620379 | |||
| 57f85476c0 | |||
| ea5c0b8601 | |||
| b46429a0ad | |||
| dbc6ecc6d8 | |||
| dbbacab105 | |||
| 4eb36d4594 | |||
| 43e02351de | |||
| 0b307bd3bc | |||
| 662a84ccf0 | |||
| 44f9bca7dc | |||
| 774b53b9b6 | |||
| 654d3bfd2b | |||
| c26d6d99c0 | |||
| 43dcc4fb12 | |||
| abae975f59 | |||
| 0e6b2a7771 |
+1
-1
@@ -37,7 +37,7 @@ typealias ToManyRelationship<Entity: Relatable> = JSONAPI.ToManyRelationship<Ent
|
|||||||
// JSON:API Documents for this particular API to have Metadata, Links,
|
// JSON:API Documents for this particular API to have Metadata, Links,
|
||||||
// useful Errors, or an APIDescription (The *SPEC* calls this
|
// useful Errors, or an APIDescription (The *SPEC* calls this
|
||||||
// "API Description" the "JSON:API Object").
|
// "API Description" the "JSON:API Object").
|
||||||
typealias Document<PrimaryResourceBody: JSONAPI.ResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
|
typealias Document<PrimaryResourceBody: JSONAPI.CodableResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<PrimaryResourceBody, NoMetadata, NoLinks, IncludeType, NoAPIDescription, BasicJSONAPIError<String>>
|
||||||
|
|
||||||
// MARK: Entity Definitions
|
// MARK: Entity Definitions
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//: [Previous](@previous)
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import JSONAPI
|
||||||
|
|
||||||
|
/*******
|
||||||
|
|
||||||
|
Please enjoy these examples, but allow me the forced casting and the lack of error checking for the sake of brevity.
|
||||||
|
|
||||||
|
This playground focuses on receiving a resource, making some changes, and then creating a request body for a PATCH request.
|
||||||
|
As with all examples in these playround pages, no actual networking code will be provided.
|
||||||
|
|
||||||
|
********/
|
||||||
|
|
||||||
|
// Mock up a server response
|
||||||
|
let mockDogData = """
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"id": "1234",
|
||||||
|
"type": "dogs",
|
||||||
|
"attributes": {
|
||||||
|
"name": "Sparky"
|
||||||
|
},
|
||||||
|
"relationships": {
|
||||||
|
"owner": {
|
||||||
|
"data": null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".data(using: .utf8)!
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: - EXAMPLE 1 (Mutable Attributes)
|
||||||
|
//
|
||||||
|
|
||||||
|
// pretend to have requested a Dog and received the mock data
|
||||||
|
// now parse it.
|
||||||
|
let parsedResponse = try! JSONDecoder().decode(MutableDogDocument.self, from: mockDogData)
|
||||||
|
|
||||||
|
// extract our Dog (skipping over any robustness to handle errors)
|
||||||
|
var dog = parsedResponse.body.primaryResource!.value
|
||||||
|
print("Received dog named: \(dog.name)")
|
||||||
|
|
||||||
|
// change the dog's name
|
||||||
|
let changedDog = dog.tappingAttributes { $0.name = .init(value: "Julia") }
|
||||||
|
|
||||||
|
// create a document to be used as a request body for a PATCH request
|
||||||
|
let patchRequest = MutableDogDocument(apiDescription: .none,
|
||||||
|
body: .init(resourceObject: changedDog),
|
||||||
|
includes: .none,
|
||||||
|
meta: .none,
|
||||||
|
links: .none)
|
||||||
|
|
||||||
|
// encode and send off to server
|
||||||
|
let encodedPatchRequest = try! JSONEncoder().encode(patchRequest)
|
||||||
|
print("----")
|
||||||
|
print(String(data: encodedPatchRequest, encoding:.utf8)!)
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: - EXAMPLE 2 (Immutable Attributes)
|
||||||
|
//
|
||||||
|
print()
|
||||||
|
print("####")
|
||||||
|
print()
|
||||||
|
|
||||||
|
// pretend to have requested a Dog and received the mock data
|
||||||
|
// now parse it.
|
||||||
|
let parsedResponse2 = try! JSONDecoder().decode(SingleDogDocument.self, from: mockDogData)
|
||||||
|
|
||||||
|
// extract our Dog (skipping over any robustness to handle errors)
|
||||||
|
var dog2 = parsedResponse2.body.primaryResource!.value
|
||||||
|
print("Received dog named: \(dog2.name)")
|
||||||
|
|
||||||
|
// change the dog's name
|
||||||
|
let changedDog2 = dog2.replacingAttributes { _ in
|
||||||
|
return .init(name: .init(value: "Nigel"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// create a document to be used as a request body for a PATCH request
|
||||||
|
let patchRequest2 = SingleDogDocument(apiDescription: .none,
|
||||||
|
body: .init(resourceObject: changedDog2),
|
||||||
|
includes: .none,
|
||||||
|
meta: .none,
|
||||||
|
links: .none)
|
||||||
|
|
||||||
|
// encode and send off to server
|
||||||
|
let encodedPatchRequest2 = try! JSONEncoder().encode(patchRequest2)
|
||||||
|
print("----")
|
||||||
|
print(String(data: encodedPatchRequest2, encoding:.utf8)!)
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: - EXAMPLE 3 (Change relationship)
|
||||||
|
//
|
||||||
|
print()
|
||||||
|
print("####")
|
||||||
|
print()
|
||||||
|
|
||||||
|
// pretend to have requested a Dog and received the mock data
|
||||||
|
// now parse it.
|
||||||
|
let parsedResponse3 = try! JSONDecoder().decode(SingleDogDocument.self, from: mockDogData)
|
||||||
|
|
||||||
|
// extract our Dog (skipping over any robustness to handle errors)
|
||||||
|
var dog3 = parsedResponse2.body.primaryResource!.value
|
||||||
|
print("Received dog with owner: \(dog3 ~> \.owner)")
|
||||||
|
|
||||||
|
// give the dog an owner
|
||||||
|
let changedDog3 = dog3.replacingRelationships { _ in
|
||||||
|
return .init(owner: .init(id: Id(rawValue: "1")))
|
||||||
|
}
|
||||||
|
|
||||||
|
// create a document to be used as a request body for a PATCH request
|
||||||
|
let patchRequest3 = SingleDogDocument(apiDescription: .none,
|
||||||
|
body: .init(resourceObject: changedDog3),
|
||||||
|
includes: .none,
|
||||||
|
meta: .none,
|
||||||
|
links: .none)
|
||||||
|
|
||||||
|
// encode and send off to server
|
||||||
|
let encodedPatchRequest3 = try! JSONEncoder().encode(patchRequest3)
|
||||||
|
print("----")
|
||||||
|
print(String(data: encodedPatchRequest3, encoding:.utf8)!)
|
||||||
@@ -64,11 +64,11 @@ if case let .data(bodyData) = peopleResponse.body {
|
|||||||
|
|
||||||
// MARK: - Work in the abstract
|
// MARK: - Work in the abstract
|
||||||
print("-----")
|
print("-----")
|
||||||
func process<T: JSONAPIDocument>(document: T) {
|
func process<T: CodableJSONAPIDocument>(document: T) {
|
||||||
guard case let .data(body) = document.body else {
|
guard let body = document.body.data else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
let x: T.Body.Data = body
|
let x: T.BodyData = body
|
||||||
}
|
}
|
||||||
process(document: peopleResponse)
|
process(document: peopleResponse)
|
||||||
|
|
||||||
|
|||||||
@@ -119,6 +119,29 @@ public enum AlternativeDogDescription: ResourceObjectDescription {
|
|||||||
|
|
||||||
public typealias AlternativeDog = ExampleEntity<AlternativeDogDescription>
|
public typealias AlternativeDog = ExampleEntity<AlternativeDogDescription>
|
||||||
|
|
||||||
|
public enum MutableDogDescription: ResourceObjectDescription {
|
||||||
|
|
||||||
|
public static var jsonType: String { return "dogs" }
|
||||||
|
|
||||||
|
public struct Attributes: JSONAPI.Attributes {
|
||||||
|
public var name: Attribute<String>
|
||||||
|
|
||||||
|
public init(name: Attribute<String>) {
|
||||||
|
self.name = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct Relationships: JSONAPI.Relationships {
|
||||||
|
public var owner: ToOne<Person?>
|
||||||
|
|
||||||
|
public init(owner: ToOne<Person?>) {
|
||||||
|
self.owner = owner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public typealias MutableDog = ExampleEntity<MutableDogDescription>
|
||||||
|
|
||||||
public extension ResourceObject where Description == DogDescription, MetaType == NoMetadata, LinksType == NoLinks, EntityRawIdType == String {
|
public extension ResourceObject where Description == DogDescription, MetaType == NoMetadata, LinksType == NoLinks, EntityRawIdType == String {
|
||||||
init(name: String, owner: Person?) throws {
|
init(name: String, owner: Person?) throws {
|
||||||
self = Dog(attributes: .init(name: .init(value: name)), relationships: DogDescription.Relationships(owner: .init(resourceObject: owner)), meta: .none, links: .none)
|
self = Dog(attributes: .init(name: .init(value: name)), relationships: DogDescription.Relationships(owner: .init(resourceObject: owner)), meta: .none, links: .none)
|
||||||
@@ -141,4 +164,6 @@ public typealias House = ExampleEntity<HouseDescription>
|
|||||||
|
|
||||||
public typealias SingleDogDocument = JSONAPI.Document<SingleResourceBody<Dog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
|
public typealias SingleDogDocument = JSONAPI.Document<SingleResourceBody<Dog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
|
||||||
|
|
||||||
|
public typealias MutableDogDocument = JSONAPI.Document<SingleResourceBody<MutableDog>, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, BasicJSONAPIError<String>>
|
||||||
|
|
||||||
public typealias BatchPeopleDocument = JSONAPI.Document<ManyResourceBody<Person>, NoMetadata, NoLinks, Include2<Dog, House>, NoAPIDescription, BasicJSONAPIError<String>>
|
public typealias BatchPeopleDocument = JSONAPI.Document<ManyResourceBody<Person>, NoMetadata, NoLinks, Include2<Dog, House>, NoAPIDescription, BasicJSONAPIError<String>>
|
||||||
|
|||||||
@@ -6,5 +6,6 @@
|
|||||||
<page name='Full Client & Server Example'/>
|
<page name='Full Client & Server Example'/>
|
||||||
<page name='Full Document Verbose Generation'/>
|
<page name='Full Document Verbose Generation'/>
|
||||||
<page name='Sparse Fieldsets Example'/>
|
<page name='Sparse Fieldsets Example'/>
|
||||||
|
<page name='PATCHing'/>
|
||||||
</pages>
|
</pages>
|
||||||
</playground>
|
</playground>
|
||||||
+2
-2
@@ -16,7 +16,7 @@ Pod::Spec.new do |spec|
|
|||||||
#
|
#
|
||||||
|
|
||||||
spec.name = "MP-JSONAPI"
|
spec.name = "MP-JSONAPI"
|
||||||
spec.version = "2.2.0"
|
spec.version = "3.0.0"
|
||||||
spec.summary = "Swift Codable JSON API framework."
|
spec.summary = "Swift Codable JSON API framework."
|
||||||
|
|
||||||
# This description is used to generate tags and improve search results.
|
# 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.requires_arc = true
|
||||||
|
|
||||||
# spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
|
# spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
|
||||||
spec.dependency "Poly", "~> 2.1"
|
spec.dependency "Poly", "~> 2.3.1"
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|||||||
+2
-2
@@ -6,8 +6,8 @@
|
|||||||
"repositoryURL": "https://github.com/mattpolzin/Poly.git",
|
"repositoryURL": "https://github.com/mattpolzin/Poly.git",
|
||||||
"state": {
|
"state": {
|
||||||
"branch": null,
|
"branch": null,
|
||||||
"revision": "4a08517b24f8e9f6dd8c02ec7da316aac5c00e2e",
|
"revision": "0c9c08204142babc480938d704a23513d11420e5",
|
||||||
"version": "2.1.0"
|
"version": "2.3.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ let package = Package(
|
|||||||
targets: ["JSONAPITesting"])
|
targets: ["JSONAPITesting"])
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.1.0")),
|
.package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.3.1")),
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
.target(
|
.target(
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
|||||||
|
//
|
||||||
|
// DocumentDecodingError.swift
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// Created by Mathew Polzin on 10/20/19.
|
||||||
|
//
|
||||||
|
|
||||||
|
public enum DocumentDecodingError: Swift.Error, Equatable {
|
||||||
|
case primaryResource(error: ResourceObjectDecodingError, idx: Int?)
|
||||||
|
case primaryResourceMissing
|
||||||
|
case primaryResourcesMissing
|
||||||
|
|
||||||
|
case includes(error: IncludesDecodingError)
|
||||||
|
|
||||||
|
case foundErrorDocumentWhenExpectingSuccess
|
||||||
|
case foundSuccessDocumentWhenExpectingError
|
||||||
|
|
||||||
|
init(_ decodingError: ResourceObjectDecodingError) {
|
||||||
|
self = .primaryResource(error: decodingError, idx: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
init(_ decodingError: ManyResourceBodyDecodingError) {
|
||||||
|
self = .primaryResource(error: decodingError.error, idx: decodingError.idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
init(_ decodingError: IncludesDecodingError) {
|
||||||
|
self = .includes(error: decodingError)
|
||||||
|
}
|
||||||
|
|
||||||
|
init?(_ decodingError: DecodingError) {
|
||||||
|
switch decodingError {
|
||||||
|
case .valueNotFound(let type, let context) where Location(context) == .data && type is AbstractResourceObject.Type:
|
||||||
|
self = .primaryResourceMissing
|
||||||
|
case .valueNotFound(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self:
|
||||||
|
self = .primaryResourcesMissing
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum Location: Equatable {
|
||||||
|
case data
|
||||||
|
|
||||||
|
init?(_ context: DecodingError.Context) {
|
||||||
|
guard context.codingPath.contains(where: { $0.stringValue == "data" }) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
self = .data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension DocumentDecodingError: CustomStringConvertible {
|
||||||
|
public var description: String {
|
||||||
|
switch self {
|
||||||
|
case .primaryResource(error: let error, idx: let idx):
|
||||||
|
let idxString = idx.map { " \($0 + 1)" } ?? ""
|
||||||
|
return "Primary Resource\(idxString) failed to parse because \(error)"
|
||||||
|
case .primaryResourceMissing:
|
||||||
|
return "Primary Resource missing."
|
||||||
|
case .primaryResourcesMissing:
|
||||||
|
return "Primary Resources array missing."
|
||||||
|
|
||||||
|
case .includes(error: let error):
|
||||||
|
return "\(error)"
|
||||||
|
|
||||||
|
case .foundErrorDocumentWhenExpectingSuccess:
|
||||||
|
return "Expected a success document with a 'data' property but found an error document."
|
||||||
|
case .foundSuccessDocumentWhenExpectingError:
|
||||||
|
return "Expected an error document but found a success document with a 'data' property."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,15 +14,15 @@ public typealias Include = EncodableJSONPoly
|
|||||||
///
|
///
|
||||||
/// If you have
|
/// If you have
|
||||||
///
|
///
|
||||||
/// `let includes: Includes<Include2<Thing1, Thing2>> = ...`
|
/// let includes: Includes<Include2<Thing1, Thing2>> = ...
|
||||||
///
|
///
|
||||||
/// then you can access all `Thing1` included resources with
|
/// then you can access all `Thing1` included resources with
|
||||||
///
|
///
|
||||||
/// `let includedThings = includes[Thing1.self]`
|
/// let includedThings = includes[Thing1.self]
|
||||||
public struct Includes<I: Include>: Encodable, Equatable {
|
public struct Includes<I: Include>: Encodable, Equatable {
|
||||||
public static var none: Includes { return .init(values: []) }
|
public static var none: Includes { return .init(values: []) }
|
||||||
|
|
||||||
let values: [I]
|
public let values: [I]
|
||||||
|
|
||||||
public init(values: [I]) {
|
public init(values: [I]) {
|
||||||
self.values = values
|
self.values = values
|
||||||
@@ -32,7 +32,7 @@ public struct Includes<I: Include>: Encodable, Equatable {
|
|||||||
var container = encoder.unkeyedContainer()
|
var container = encoder.unkeyedContainer()
|
||||||
|
|
||||||
guard I.self != NoIncludes.self else {
|
guard I.self != NoIncludes.self else {
|
||||||
throw JSONAPIEncodingError.illegalEncoding("Attempting to encode Include0, which should be represented by the absense of an 'included' entry altogether.")
|
throw JSONAPICodingError.illegalEncoding("Attempting to encode Include0, which should be represented by the absense of an 'included' entry altogether.", path: encoder.codingPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
for value in values {
|
for value in values {
|
||||||
@@ -56,8 +56,35 @@ extension Includes: Decodable where I: Decodable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var valueAggregator = [I]()
|
var valueAggregator = [I]()
|
||||||
|
var idx = 0
|
||||||
while !container.isAtEnd {
|
while !container.isAtEnd {
|
||||||
|
do {
|
||||||
valueAggregator.append(try container.decode(I.self))
|
valueAggregator.append(try container.decode(I.self))
|
||||||
|
idx = idx + 1
|
||||||
|
} catch let error as PolyDecodeNoTypesMatchedError {
|
||||||
|
let errors: [ResourceObjectDecodingError] = error
|
||||||
|
.individualTypeFailures
|
||||||
|
.compactMap { decodingError in
|
||||||
|
switch decodingError.error {
|
||||||
|
case .typeMismatch(_, let context),
|
||||||
|
.valueNotFound(_, let context),
|
||||||
|
.keyNotFound(_, let context),
|
||||||
|
.dataCorrupted(let context):
|
||||||
|
return context.underlyingError as? ResourceObjectDecodingError
|
||||||
|
@unknown default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard errors.count == error.individualTypeFailures.count else {
|
||||||
|
throw IncludesDecodingError(error: error, idx: idx)
|
||||||
|
}
|
||||||
|
throw IncludesDecodingError(
|
||||||
|
error: IncludeDecodingError(failures: errors),
|
||||||
|
idx: idx
|
||||||
|
)
|
||||||
|
} catch let error {
|
||||||
|
throw IncludesDecodingError(error: error, idx: idx)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
values = valueAggregator
|
values = valueAggregator
|
||||||
@@ -169,3 +196,40 @@ extension Includes where I: _Poly10 {
|
|||||||
return values.compactMap { $0.j }
|
return values.compactMap { $0.j }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - 11 includes
|
||||||
|
public typealias Include11 = Poly11
|
||||||
|
extension Includes where I: _Poly11 {
|
||||||
|
public subscript(_ lookup: I.K.Type) -> [I.K] {
|
||||||
|
return values.compactMap { $0.k }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - DecodingError
|
||||||
|
public struct IncludesDecodingError: Swift.Error, Equatable {
|
||||||
|
public let error: Swift.Error
|
||||||
|
public let idx: Int
|
||||||
|
|
||||||
|
public static func ==(lhs: Self, rhs: Self) -> Bool {
|
||||||
|
return lhs.idx == rhs.idx
|
||||||
|
&& String(describing: lhs) == String(describing: rhs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension IncludesDecodingError: CustomStringConvertible {
|
||||||
|
public var description: String {
|
||||||
|
return "Include \(idx + 1) failed to parse: \(error)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct IncludeDecodingError: Swift.Error, Equatable, CustomStringConvertible {
|
||||||
|
public let failures: [ResourceObjectDecodingError]
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
return failures
|
||||||
|
.enumerated()
|
||||||
|
.map {
|
||||||
|
"\nCould not have been Include Type \($0.offset + 1) because:\n\($0.element)"
|
||||||
|
}.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,60 +10,60 @@
|
|||||||
/// array should be used for no results).
|
/// array should be used for no results).
|
||||||
public protocol OptionalEncodablePrimaryResource: Equatable, Encodable {}
|
public protocol OptionalEncodablePrimaryResource: Equatable, Encodable {}
|
||||||
|
|
||||||
/// An `EncodablePrimaryResource` is a `PrimaryResource` that only supports encoding.
|
/// An `EncodablePrimaryResource` is a `CodablePrimaryResource` that only supports encoding.
|
||||||
/// This is actually more restrictave than `PrimaryResource`, which supports both encoding and
|
|
||||||
/// decoding.
|
|
||||||
public protocol EncodablePrimaryResource: OptionalEncodablePrimaryResource {}
|
public protocol EncodablePrimaryResource: OptionalEncodablePrimaryResource {}
|
||||||
|
|
||||||
/// This protocol allows for `SingleResourceBody` to contain a `null`
|
/// This protocol allows for `SingleResourceBody` to contain a `null`
|
||||||
/// data object where `ManyResourceBody` cannot (because an empty
|
/// data object where `ManyResourceBody` cannot (because an empty
|
||||||
/// array should be used for no results).
|
/// array should be used for no results).
|
||||||
public protocol OptionalPrimaryResource: OptionalEncodablePrimaryResource, Decodable {}
|
public protocol OptionalCodablePrimaryResource: OptionalEncodablePrimaryResource, Decodable {}
|
||||||
|
|
||||||
/// A `PrimaryResource` is a type that can be used in the body of a JSON API
|
/// A `CodablePrimaryResource` is a type that can be used in the body of a JSON API
|
||||||
/// document as the primary resource.
|
/// document as the primary resource.
|
||||||
public protocol PrimaryResource: EncodablePrimaryResource, OptionalPrimaryResource {}
|
public protocol CodablePrimaryResource: EncodablePrimaryResource, OptionalCodablePrimaryResource {}
|
||||||
|
|
||||||
extension Optional: OptionalEncodablePrimaryResource where Wrapped: EncodablePrimaryResource {}
|
extension Optional: OptionalEncodablePrimaryResource where Wrapped: EncodablePrimaryResource {}
|
||||||
|
|
||||||
extension Optional: OptionalPrimaryResource where Wrapped: PrimaryResource {}
|
extension Optional: OptionalCodablePrimaryResource where Wrapped: CodablePrimaryResource {}
|
||||||
|
|
||||||
/// An `EncodableResourceBody` is a `ResourceBody` that only supports being
|
/// An `EncodableResourceBody` is a `ResourceBody` that only supports being
|
||||||
/// encoded. It is actually weaker than `ResourceBody`, which supports both encoding
|
/// encoded. It is actually weaker than `ResourceBody`, which supports both encoding
|
||||||
/// and decoding.
|
/// and decoding.
|
||||||
public protocol EncodableResourceBody: Equatable, Encodable {}
|
public protocol EncodableResourceBody: Equatable, Encodable {
|
||||||
|
associatedtype PrimaryResource
|
||||||
|
}
|
||||||
|
|
||||||
/// A ResourceBody is a representation of the body of the JSON API Document.
|
/// A `CodableResourceBody` is a representation of the body of the JSON:API Document.
|
||||||
/// It can either be one resource (which can be specified as optional or not)
|
/// It can either be one resource (which can be specified as optional or not)
|
||||||
/// or it can contain many resources (and array with zero or more entries).
|
/// or it can contain many resources (and array with zero or more entries).
|
||||||
public protocol ResourceBody: Decodable, EncodableResourceBody {}
|
public protocol CodableResourceBody: Decodable, EncodableResourceBody {}
|
||||||
|
|
||||||
/// A `ResourceBody` that has the ability to take on more primary
|
/// A `ResourceBody` that has the ability to take on more primary
|
||||||
/// resources by appending another similarly typed `ResourceBody`.
|
/// resources by appending another similarly typed `ResourceBody`.
|
||||||
public protocol Appendable {
|
public protocol ResourceBodyAppendable {
|
||||||
func appending(_ other: Self) -> Self
|
func appending(_ other: Self) -> Self
|
||||||
}
|
}
|
||||||
|
|
||||||
public func +<R: Appendable>(_ left: R, right: R) -> R {
|
public func +<R: ResourceBodyAppendable>(_ left: R, right: R) -> R {
|
||||||
return left.appending(right)
|
return left.appending(right)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A type allowing for a document body containing 1 primary resource.
|
/// A type allowing for a document body containing 1 primary resource.
|
||||||
/// If the `Entity` specialization is an `Optional` type, the body can contain
|
/// If the `Entity` specialization is an `Optional` type, the body can contain
|
||||||
/// 0 or 1 primary resources.
|
/// 0 or 1 primary resources.
|
||||||
public struct SingleResourceBody<Entity: JSONAPI.OptionalEncodablePrimaryResource>: EncodableResourceBody {
|
public struct SingleResourceBody<PrimaryResource: JSONAPI.OptionalEncodablePrimaryResource>: EncodableResourceBody {
|
||||||
public let value: Entity
|
public let value: PrimaryResource
|
||||||
|
|
||||||
public init(resourceObject: Entity) {
|
public init(resourceObject: PrimaryResource) {
|
||||||
self.value = resourceObject
|
self.value = resourceObject
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A type allowing for a document body containing 0 or more primary resources.
|
/// A type allowing for a document body containing 0 or more primary resources.
|
||||||
public struct ManyResourceBody<Entity: JSONAPI.EncodablePrimaryResource>: EncodableResourceBody, Appendable {
|
public struct ManyResourceBody<PrimaryResource: JSONAPI.EncodablePrimaryResource>: EncodableResourceBody, ResourceBodyAppendable {
|
||||||
public let values: [Entity]
|
public let values: [PrimaryResource]
|
||||||
|
|
||||||
public init(resourceObjects: [Entity]) {
|
public init(resourceObjects: [PrimaryResource]) {
|
||||||
values = resourceObjects
|
values = resourceObjects
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +74,9 @@ public struct ManyResourceBody<Entity: JSONAPI.EncodablePrimaryResource>: Encoda
|
|||||||
|
|
||||||
/// Use NoResourceBody to indicate you expect a JSON API document to not
|
/// Use NoResourceBody to indicate you expect a JSON API document to not
|
||||||
/// contain a "data" top-level key.
|
/// contain a "data" top-level key.
|
||||||
public struct NoResourceBody: ResourceBody {
|
public struct NoResourceBody: CodableResourceBody {
|
||||||
|
public typealias PrimaryResource = Void
|
||||||
|
|
||||||
public static var none: NoResourceBody { return NoResourceBody() }
|
public static var none: NoResourceBody { return NoResourceBody() }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +86,7 @@ extension SingleResourceBody {
|
|||||||
var container = encoder.singleValueContainer()
|
var container = encoder.singleValueContainer()
|
||||||
|
|
||||||
let anyNil: Any? = nil
|
let anyNil: Any? = nil
|
||||||
let nilValue = anyNil as? Entity
|
let nilValue = anyNil as? PrimaryResource
|
||||||
guard value != nilValue else {
|
guard value != nilValue else {
|
||||||
try container.encodeNil()
|
try container.encodeNil()
|
||||||
return
|
return
|
||||||
@@ -94,18 +96,18 @@ extension SingleResourceBody {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SingleResourceBody: Decodable, ResourceBody where Entity: OptionalPrimaryResource {
|
extension SingleResourceBody: Decodable, CodableResourceBody where PrimaryResource: OptionalCodablePrimaryResource {
|
||||||
public init(from decoder: Decoder) throws {
|
public init(from decoder: Decoder) throws {
|
||||||
let container = try decoder.singleValueContainer()
|
let container = try decoder.singleValueContainer()
|
||||||
|
|
||||||
let anyNil: Any? = nil
|
let anyNil: Any? = nil
|
||||||
if container.decodeNil(),
|
if container.decodeNil(),
|
||||||
let val = anyNil as? Entity {
|
let val = anyNil as? PrimaryResource {
|
||||||
value = val
|
value = val
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
value = try container.decode(Entity.self)
|
value = try container.decode(PrimaryResource.self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,12 +121,21 @@ extension ManyResourceBody {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ManyResourceBody: Decodable, ResourceBody where Entity: PrimaryResource {
|
extension ManyResourceBody: Decodable, CodableResourceBody where PrimaryResource: CodablePrimaryResource {
|
||||||
public init(from decoder: Decoder) throws {
|
public init(from decoder: Decoder) throws {
|
||||||
var container = try decoder.unkeyedContainer()
|
var container = try decoder.unkeyedContainer()
|
||||||
var valueAggregator = [Entity]()
|
var valueAggregator = [PrimaryResource]()
|
||||||
|
var idx = 0
|
||||||
while !container.isAtEnd {
|
while !container.isAtEnd {
|
||||||
valueAggregator.append(try container.decode(Entity.self))
|
do {
|
||||||
|
valueAggregator.append(try container.decode(PrimaryResource.self))
|
||||||
|
} catch let error as ResourceObjectDecodingError {
|
||||||
|
throw ManyResourceBodyDecodingError(
|
||||||
|
error: error,
|
||||||
|
idx: idx
|
||||||
|
)
|
||||||
|
}
|
||||||
|
idx = idx + 1
|
||||||
}
|
}
|
||||||
values = valueAggregator
|
values = valueAggregator
|
||||||
}
|
}
|
||||||
@@ -143,3 +154,9 @@ extension ManyResourceBody: CustomStringConvertible {
|
|||||||
return "PrimaryResourceBody(\(String(describing: values)))"
|
return "PrimaryResourceBody(\(String(describing: values)))"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - DecodingError
|
||||||
|
public struct ManyResourceBodyDecodingError: Swift.Error, Equatable {
|
||||||
|
public let error: ResourceObjectDecodingError
|
||||||
|
public let idx: Int
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
//
|
|
||||||
// EncodingError.swift
|
|
||||||
// JSONAPI
|
|
||||||
//
|
|
||||||
// Created by Mathew Polzin on 12/7/18.
|
|
||||||
//
|
|
||||||
|
|
||||||
public enum JSONAPIEncodingError: Swift.Error {
|
|
||||||
case typeMismatch(expected: String, found: String)
|
|
||||||
case illegalEncoding(String)
|
|
||||||
case illegalDecoding(String)
|
|
||||||
case missingOrMalformedMetadata
|
|
||||||
case missingOrMalformedLinks
|
|
||||||
}
|
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
//
|
//
|
||||||
// BasicError.swift
|
// BasicJSONAPIError.swift
|
||||||
// JSONAPI
|
// JSONAPI
|
||||||
//
|
//
|
||||||
// Created by Mathew Polzin on 9/29/19.
|
// Created by Mathew Polzin on 9/29/19.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// Most of the JSON:API Spec defined Error fields.
|
/// Most of the JSON:API Spec defined Error fields.
|
||||||
public struct BasicJSONAPIErrorPayload<IdType: Codable & Equatable>: Codable, Equatable, ErrorDictType {
|
public struct BasicJSONAPIErrorPayload<IdType: Codable & Equatable>: Codable, Equatable, ErrorDictType, CustomStringConvertible {
|
||||||
/// a unique identifier for this particular occurrence of the problem
|
/// a unique identifier for this particular occurrence of the problem
|
||||||
public let id: IdType?
|
public let id: IdType?
|
||||||
// public let links: Links? // we skip this for now to avoid adding complexity to using this basic type.
|
|
||||||
|
// 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
|
/// the HTTP status code applicable to this problem
|
||||||
public let status: String?
|
public let status: String?
|
||||||
/// an application-specific error code
|
/// an application-specific error code
|
||||||
@@ -20,7 +22,8 @@ public struct BasicJSONAPIErrorPayload<IdType: Codable & Equatable>: Codable, Eq
|
|||||||
public let detail: String?
|
public let detail: String?
|
||||||
/// an object containing references to the source of the error
|
/// an object containing references to the source of the error
|
||||||
public let source: Source?
|
public let source: Source?
|
||||||
// public let meta: Meta? // we skip this for now to avoid adding complexity to using this basic type
|
|
||||||
|
// public let meta: Meta? // we skip this for now to avoid adding complexity to using this basic type
|
||||||
|
|
||||||
public init(id: IdType? = nil,
|
public init(id: IdType? = nil,
|
||||||
status: String? = nil,
|
status: String? = nil,
|
||||||
@@ -61,6 +64,10 @@ public struct BasicJSONAPIErrorPayload<IdType: Codable & Equatable>: Codable, Eq
|
|||||||
].compactMap { $0 }
|
].compactMap { $0 }
|
||||||
return Dictionary(uniqueKeysWithValues: keysAndValues)
|
return Dictionary(uniqueKeysWithValues: keysAndValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
return definedFields.map { "\($0.key): \($0.value)" }.sorted().joined(separator: ", ")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `BasicJSONAPIError` optionally decodes many possible fields
|
/// `BasicJSONAPIError` optionally decodes many possible fields
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//
|
//
|
||||||
// GenericError.swift
|
// GenericJSONAPIError.swift
|
||||||
// JSONAPI
|
// JSONAPI
|
||||||
//
|
//
|
||||||
// Created by Mathew Polzin on 9/29/19.
|
// Created by Mathew Polzin on 9/29/19.
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
/// `GenericJSONAPIError` can be used to specify whatever error
|
/// `GenericJSONAPIError` can be used to specify whatever error
|
||||||
/// payload you expect to need to parse in responses and handle any
|
/// payload you expect to need to parse in responses and handle any
|
||||||
/// other payload structure as `.unknownError`.
|
/// other payload structure as `.unknownError`.
|
||||||
public enum GenericJSONAPIError<ErrorPayload: Codable & Equatable>: JSONAPIError {
|
public enum GenericJSONAPIError<ErrorPayload: Codable & Equatable>: JSONAPIError, CustomStringConvertible {
|
||||||
case unknownError
|
case unknownError
|
||||||
case error(ErrorPayload)
|
case error(ErrorPayload)
|
||||||
|
|
||||||
@@ -35,6 +35,15 @@ public enum GenericJSONAPIError<ErrorPayload: Codable & Equatable>: JSONAPIError
|
|||||||
public static var unknown: Self {
|
public static var unknown: Self {
|
||||||
return .unknownError
|
return .unknownError
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
switch self {
|
||||||
|
case .unknownError:
|
||||||
|
return "unknown error"
|
||||||
|
case .error(let payload):
|
||||||
|
return String(describing: payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public extension GenericJSONAPIError {
|
public extension GenericJSONAPIError {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//
|
//
|
||||||
// Error.swift
|
// JSONAPIError.swift
|
||||||
// JSONAPI
|
// JSONAPI
|
||||||
//
|
//
|
||||||
// Created by Mathew Polzin on 11/10/18.
|
// Created by Mathew Polzin on 11/10/18.
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
//
|
||||||
|
// JSONAPICodingError.swift
|
||||||
|
// JSONAPI
|
||||||
|
//
|
||||||
|
// Created by Mathew Polzin on 12/7/18.
|
||||||
|
//
|
||||||
|
|
||||||
|
public enum JSONAPICodingError: Swift.Error {
|
||||||
|
case typeMismatch(expected: String, found: String, path: [CodingKey])
|
||||||
|
case quantityMismatch(expected: Quantity, path: [CodingKey])
|
||||||
|
case illegalEncoding(String, path: [CodingKey])
|
||||||
|
case illegalDecoding(String, path: [CodingKey])
|
||||||
|
case missingOrMalformedMetadata(path: [CodingKey])
|
||||||
|
case missingOrMalformedLinks(path: [CodingKey])
|
||||||
|
|
||||||
|
public enum Quantity: String, Equatable {
|
||||||
|
case one
|
||||||
|
case many
|
||||||
|
|
||||||
|
public var other: Quantity {
|
||||||
|
switch self {
|
||||||
|
case .one: return .many
|
||||||
|
case .many: return .one
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
// Created by Mathew Polzin on 11/24/18.
|
// Created by Mathew Polzin on 11/24/18.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// A Links structure should contain nothing but JSONAPI.Link properties.
|
/// A Links structure should contain nothing but `JSONAPI.Link` properties.
|
||||||
public protocol Links: Codable, Equatable {}
|
public protocol Links: Codable, Equatable {}
|
||||||
|
|
||||||
/// Use NoLinks where no links should belong to a JSON API component
|
/// Use NoLinks where no links should belong to a JSON API component
|
||||||
|
|||||||
@@ -6,17 +6,17 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
/// Conform a type to this protocol to indicate it can be encoded to or decoded from
|
/// Conform a type to this protocol to indicate it can be encoded to or decoded from
|
||||||
/// the meta data attached to a component of a JSON API document. Different meta data
|
/// the meta data attached to a component of a JSON:API document. Different meta data
|
||||||
/// can be stored all over the place: On the root document, on a resource object, on
|
/// can be stored all over the place: On the root document, on a resource object, on
|
||||||
/// link objects, etc.
|
/// link objects, etc.
|
||||||
///
|
///
|
||||||
/// JSON API Metadata is totally open ended. It can take whatever JSON-compliant structure
|
/// JSON:API Metadata is totally open ended. It can take whatever JSON-compliant structure
|
||||||
/// the server and client agree upon.
|
/// the server and client agree upon.
|
||||||
public protocol Meta: Codable, Equatable {
|
public protocol Meta: Codable, Equatable {
|
||||||
}
|
}
|
||||||
|
|
||||||
// We make Optional a Meta if it wraps a Meta so that Metadata can be specified as
|
// We make Optional a Meta if it wraps a Meta so that
|
||||||
// nullable.
|
// Metadata can be specified as nullable.
|
||||||
extension Optional: Meta where Wrapped: Meta {}
|
extension Optional: Meta where Wrapped: Meta {}
|
||||||
|
|
||||||
/// Use this type when you want to specify not to encode or decode any metadata
|
/// Use this type when you want to specify not to encode or decode any metadata
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user