From b8b94a4c8641af22a9c8cc58952ffb56e1c3975f Mon Sep 17 00:00:00 2001 From: = <=> Date: Sun, 6 Mar 2022 00:31:39 -0800 Subject: [PATCH 01/33] loosen podspec Poly requirement. Bump patch version. --- JSONAPI.podspec | 4 ++-- README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/JSONAPI.podspec b/JSONAPI.podspec index 5cf8785..19e5c0e 100644 --- a/JSONAPI.podspec +++ b/JSONAPI.podspec @@ -16,7 +16,7 @@ Pod::Spec.new do |spec| # spec.name = "MP-JSONAPI" - spec.version = "5.0.0" + spec.version = "5.0.2" 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.4.0" + spec.dependency "Poly", "~> 2.4" end diff --git a/README.md b/README.md index 878fcdf..c74fb68 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ If you find something wrong with this library and it isn't already mentioned und ### Swift Package Manager Just include the following in your package's dependencies and add `JSONAPI` to the dependencies for any of your targets. ```swift -.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "5.0.0") +.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "5.0.2") ``` ### Xcode project From 575199e775d6afebcbb497edeccbbe2c7933d7cc Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:07:44 -0700 Subject: [PATCH 02/33] Add Include12 and Include13 types. --- .github/workflows/tests.yml | 5 + Package.resolved | 4 +- Package.swift | 2 +- .../JSONAPI/Document/CompoundResource.swift | 2 +- Sources/JSONAPI/Document/Includes.swift | 16 ++ .../Resource/Poly+PrimaryResource.swift | 64 ++++++ .../Comparisons/DocumentDataCompare.swift | 2 +- .../JSONAPITests/Includes/IncludeTests.swift | 69 +++++++ .../Includes/stubs/IncludeStubs.swift | 189 ++++++++++++++++++ 9 files changed, 348 insertions(+), 5 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2e0ea6f..3386cdf 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -28,6 +28,11 @@ jobs: - swift:5.4-focal - swift:5.4-centos8 - swift:5.4-amazonlinux2 + - swift:5.5-xenial + - swift:5.5-bionic + - swift:5.5-focal + - swift:5.5-centos8 + - swift:5.5-amazonlinux2 container: ${{ matrix.image }} steps: - name: Checkout code diff --git a/Package.resolved b/Package.resolved index 63465c7..8a582ff 100644 --- a/Package.resolved +++ b/Package.resolved @@ -6,8 +6,8 @@ "repositoryURL": "https://github.com/mattpolzin/Poly.git", "state": { "branch": null, - "revision": "36ba3f624bffa34f5f9b9c7648eab3cfdcab4748", - "version": "2.5.0" + "revision": "c108e9e0a2904134719b082f6c18d64406afc6db", + "version": "2.6.0" } } ] diff --git a/Package.swift b/Package.swift index 3762356..e7a0e51 100644 --- a/Package.swift +++ b/Package.swift @@ -17,7 +17,7 @@ let package = Package( targets: ["JSONAPITesting"]) ], dependencies: [ - .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.4.0")), + .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.6.0")), ], targets: [ .target( diff --git a/Sources/JSONAPI/Document/CompoundResource.swift b/Sources/JSONAPI/Document/CompoundResource.swift index 9ad84fe..9baaf2f 100644 --- a/Sources/JSONAPI/Document/CompoundResource.swift +++ b/Sources/JSONAPI/Document/CompoundResource.swift @@ -71,7 +71,7 @@ extension Sequence where Element: CompoundResourceProtocol { } } -extension EncodableJSONAPIDocument where PrimaryResourceBody: EncodableResourceBody, PrimaryResourceBody.PrimaryResource: ResourceObjectType { +extension EncodableJSONAPIDocument where PrimaryResourceBody.PrimaryResource: ResourceObjectType { public typealias CompoundResource = JSONAPI.CompoundResource } diff --git a/Sources/JSONAPI/Document/Includes.swift b/Sources/JSONAPI/Document/Includes.swift index e48a547..30634ae 100644 --- a/Sources/JSONAPI/Document/Includes.swift +++ b/Sources/JSONAPI/Document/Includes.swift @@ -206,6 +206,22 @@ extension Includes where I: _Poly11 { } } +// MARK: - 12 includes +public typealias Include12 = Poly12 +extension Includes where I: _Poly12 { + public subscript(_ lookup: I.L.Type) -> [I.L] { + return values.compactMap(\.l) + } +} + +// MARK: - 13 includes +public typealias Include13 = Poly13 +extension Includes where I: _Poly13 { + public subscript(_ lookup: I.M.Type) -> [I.M] { + return values.compactMap(\.m) + } +} + // MARK: - DecodingError public struct IncludesDecodingError: Swift.Error, Equatable { public let error: Swift.Error diff --git a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift index 73c1246..0dab925 100644 --- a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift +++ b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift @@ -162,3 +162,67 @@ extension Poly11: CodablePrimaryResource, OptionalCodablePrimaryResource I: CodablePolyWrapped, J: CodablePolyWrapped, K: CodablePolyWrapped {} + +// MARK: - 12 types +extension Poly12: EncodablePrimaryResource, OptionalEncodablePrimaryResource +where +A: EncodablePolyWrapped, +B: EncodablePolyWrapped, +C: EncodablePolyWrapped, +D: EncodablePolyWrapped, +E: EncodablePolyWrapped, +F: EncodablePolyWrapped, +G: EncodablePolyWrapped, +H: EncodablePolyWrapped, +I: EncodablePolyWrapped, +J: EncodablePolyWrapped, +K: EncodablePolyWrapped, +L: EncodablePolyWrapped {} + +extension Poly12: CodablePrimaryResource, OptionalCodablePrimaryResource +where +A: CodablePolyWrapped, +B: CodablePolyWrapped, +C: CodablePolyWrapped, +D: CodablePolyWrapped, +E: CodablePolyWrapped, +F: CodablePolyWrapped, +G: CodablePolyWrapped, +H: CodablePolyWrapped, +I: CodablePolyWrapped, +J: CodablePolyWrapped, +K: CodablePolyWrapped, +L: CodablePolyWrapped {} + +// MARK: - 13 types +extension Poly13: EncodablePrimaryResource, OptionalEncodablePrimaryResource +where +A: EncodablePolyWrapped, +B: EncodablePolyWrapped, +C: EncodablePolyWrapped, +D: EncodablePolyWrapped, +E: EncodablePolyWrapped, +F: EncodablePolyWrapped, +G: EncodablePolyWrapped, +H: EncodablePolyWrapped, +I: EncodablePolyWrapped, +J: EncodablePolyWrapped, +K: EncodablePolyWrapped, +L: EncodablePolyWrapped, +M: EncodablePolyWrapped {} + +extension Poly13: CodablePrimaryResource, OptionalCodablePrimaryResource +where +A: CodablePolyWrapped, +B: CodablePolyWrapped, +C: CodablePolyWrapped, +D: CodablePolyWrapped, +E: CodablePolyWrapped, +F: CodablePolyWrapped, +G: CodablePolyWrapped, +H: CodablePolyWrapped, +I: CodablePolyWrapped, +J: CodablePolyWrapped, +K: CodablePolyWrapped, +L: CodablePolyWrapped, +M: CodablePolyWrapped {} diff --git a/Sources/JSONAPITesting/Comparisons/DocumentDataCompare.swift b/Sources/JSONAPITesting/Comparisons/DocumentDataCompare.swift index da7f27e..be2cad6 100644 --- a/Sources/JSONAPITesting/Comparisons/DocumentDataCompare.swift +++ b/Sources/JSONAPITesting/Comparisons/DocumentDataCompare.swift @@ -86,7 +86,7 @@ public struct ManyResourceObjectComparison: Equatable, PropertyComparison { } } -extension TestableResourceBody where TestablePrimaryResourceType: ResourceObjectType { +extension TestableResourceBody { public func compare(to other: Self) -> PrimaryResourceBodyComparison { guard let one = testableResourceObject, let two = other.testableResourceObject else { diff --git a/Tests/JSONAPITests/Includes/IncludeTests.swift b/Tests/JSONAPITests/Includes/IncludeTests.swift index 6da21e5..e0a44a4 100644 --- a/Tests/JSONAPITests/Includes/IncludeTests.swift +++ b/Tests/JSONAPITests/Includes/IncludeTests.swift @@ -219,6 +219,53 @@ class IncludedTests: XCTestCase { test_DecodeEncodeEquality(type: Includes>.self, data: eleven_different_type_includes) } + + func test_TwelveDifferentIncludes() { + let includes = decoded(type: Includes>.self, + data: twelve_different_type_includes) + + XCTAssertEqual(includes[TestEntity.self].count, 1) + XCTAssertEqual(includes[TestEntity2.self].count, 1) + XCTAssertEqual(includes[TestEntity3.self].count, 1) + XCTAssertEqual(includes[TestEntity4.self].count, 1) + XCTAssertEqual(includes[TestEntity5.self].count, 1) + XCTAssertEqual(includes[TestEntity6.self].count, 1) + XCTAssertEqual(includes[TestEntity7.self].count, 1) + XCTAssertEqual(includes[TestEntity8.self].count, 1) + XCTAssertEqual(includes[TestEntity9.self].count, 1) + XCTAssertEqual(includes[TestEntity10.self].count, 1) + XCTAssertEqual(includes[TestEntity11.self].count, 1) + XCTAssertEqual(includes[TestEntity12.self].count, 1) + } + + func test_TwelveDifferentIncludes_encode() { + test_DecodeEncodeEquality(type: Includes>.self, + data: twelve_different_type_includes) + } + + func test_ThirteenDifferentIncludes() { + let includes = decoded(type: Includes>.self, + data: thirteen_different_type_includes) + + XCTAssertEqual(includes[TestEntity.self].count, 1) + XCTAssertEqual(includes[TestEntity2.self].count, 1) + XCTAssertEqual(includes[TestEntity3.self].count, 1) + XCTAssertEqual(includes[TestEntity4.self].count, 1) + XCTAssertEqual(includes[TestEntity5.self].count, 1) + XCTAssertEqual(includes[TestEntity6.self].count, 1) + XCTAssertEqual(includes[TestEntity7.self].count, 1) + XCTAssertEqual(includes[TestEntity8.self].count, 1) + XCTAssertEqual(includes[TestEntity9.self].count, 1) + XCTAssertEqual(includes[TestEntity10.self].count, 1) + XCTAssertEqual(includes[TestEntity11.self].count, 1) + XCTAssertEqual(includes[TestEntity12.self].count, 1) + XCTAssertEqual(includes[TestEntity13.self].count, 1) + } + + func test_ThirteenDifferentIncludes_encode() { + test_DecodeEncodeEquality(type: Includes>.self, + data: thirteen_different_type_includes) + } } // MARK: - Appending @@ -536,4 +583,26 @@ extension IncludedTests { } typealias TestEntity11 = BasicEntity + + enum TestEntityType12: ResourceObjectDescription { + + typealias Attributes = NoAttributes + + public static var jsonType: String { return "test_entity12" } + + typealias Relationships = NoRelationships + } + + typealias TestEntity12 = BasicEntity + + enum TestEntityType13: ResourceObjectDescription { + + typealias Attributes = NoAttributes + + public static var jsonType: String { return "test_entity13" } + + typealias Relationships = NoRelationships + } + + typealias TestEntity13 = BasicEntity } diff --git a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift index 708e154..2cfd3fa 100644 --- a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift +++ b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift @@ -687,6 +687,195 @@ let eleven_different_type_includes = """ ] """.data(using: .utf8)! +let twelve_different_type_includes = """ +[ + { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF", + "attributes": { + "foo": "Hello", + "bar": 123 + } + }, + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333", + "attributes": { + "foo": "World", + "bar": 456 + }, + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + } + } + }, + { + "type": "test_entity3", + "id": "11223B69-4DF1-467F-B52E-B0C9E44FC443", + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + }, + "entity2": { + "data": [ + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333" + } + ] + } + } + }, + { + "type": "test_entity6", + "id": "11113B69-4DF1-467F-B52E-B0C9E44FC444", + "relationships": { + "entity4": { + "data": { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + } + } + } + }, + { + "type": "test_entity5", + "id": "A24B3B69-4DF1-467F-B52E-B0C9E44F436A" + }, + { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity7", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity8", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F266F" + }, + { + "type": "test_entity9", + "id": "364B3B69-4DF1-218F-B52E-B0C9E44F2661" + }, + { + "type": "test_entity10", + "id": "264B3B69-4DF1-212F-B52E-B0C9E44F2660" + }, + { + "type": "test_entity11", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C0B" + }, + { + "type": "test_entity12", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C00" + } +] +""".data(using: .utf8)! + +let thirteen_different_type_includes = """ +[ + { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF", + "attributes": { + "foo": "Hello", + "bar": 123 + } + }, + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333", + "attributes": { + "foo": "World", + "bar": 456 + }, + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + } + } + }, + { + "type": "test_entity3", + "id": "11223B69-4DF1-467F-B52E-B0C9E44FC443", + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + }, + "entity2": { + "data": [ + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333" + } + ] + } + } + }, + { + "type": "test_entity6", + "id": "11113B69-4DF1-467F-B52E-B0C9E44FC444", + "relationships": { + "entity4": { + "data": { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + } + } + } + }, + { + "type": "test_entity5", + "id": "A24B3B69-4DF1-467F-B52E-B0C9E44F436A" + }, + { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity7", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity8", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F266F" + }, + { + "type": "test_entity9", + "id": "364B3B69-4DF1-218F-B52E-B0C9E44F2661" + }, + { + "type": "test_entity10", + "id": "264B3B69-4DF1-212F-B52E-B0C9E44F2660" + }, + { + "type": "test_entity11", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C0B" + }, + { + "type": "test_entity12", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C00" + }, + { + "type": "test_entity13", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C01" + } +] +""".data(using: .utf8)! let three_includes_one_missing_attributes = """ [ From 91639846031a4a3fae32d1b470b5cf404c2833f9 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:08:56 -0700 Subject: [PATCH 03/33] bump podspec versions --- JSONAPI.podspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONAPI.podspec b/JSONAPI.podspec index 19e5c0e..4a22764 100644 --- a/JSONAPI.podspec +++ b/JSONAPI.podspec @@ -16,7 +16,7 @@ Pod::Spec.new do |spec| # spec.name = "MP-JSONAPI" - spec.version = "5.0.2" + spec.version = "5.1.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.4" + spec.dependency "Poly", "~> 2.6" end From f7e5df3d5e21b385587c368d80e90a1f736beb76 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:09:51 -0700 Subject: [PATCH 04/33] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c74fb68..c42c9d7 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ If you find something wrong with this library and it isn't already mentioned und ### Swift Package Manager Just include the following in your package's dependencies and add `JSONAPI` to the dependencies for any of your targets. ```swift -.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "5.0.2") +.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "5.1.0") ``` ### Xcode project From 022611713f5a99294ab1c46ea6d63bc481e89610 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:11:21 -0700 Subject: [PATCH 05/33] Add swift 5.6 linux images to tests as well. --- .github/workflows/tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3386cdf..00fc0fe 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -33,6 +33,11 @@ jobs: - swift:5.5-focal - swift:5.5-centos8 - swift:5.5-amazonlinux2 + - swift:5.6-xenial + - swift:5.6-bionic + - swift:5.6-focal + - swift:5.6-centos8 + - swift:5.6-amazonlinux2 container: ${{ matrix.image }} steps: - name: Checkout code From a6ffeab1cb225f87323f218b327b84c83a908e00 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:24:55 -0700 Subject: [PATCH 06/33] See if this fixes latest linux swift versions. --- .../Resource Object/ResourceObjectDecodingError.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift b/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift index 7ca4c04..72f0a2a 100644 --- a/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift +++ b/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift @@ -117,9 +117,16 @@ public struct ResourceObjectDecodingError: Swift.Error, Equatable { location = .type } + let subjectPath: [CodingKey] + if location == .relationships && path.last?.stringValue == "data" { + subjectPath = path.dropLast() + } else { + subjectPath = path + } + return ( location, - name: path.last?.stringValue ?? "unnamed" + name: subjectPath.last?.stringValue ?? "unnamed" ) } } From fd412a4ccd9e3b6fa36ca7e36931a2c00708689a Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:49:31 -0700 Subject: [PATCH 07/33] slowly fixing latest swift version linux tests --- .../ResourceObjectDecodingErrorTests.swift | 96 ++++++++++++++----- 1 file changed, 72 insertions(+), 24 deletions(-) diff --git a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift index 6597293..3003dae 100644 --- a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift +++ b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift @@ -103,20 +103,44 @@ final class ResourceObjectDecodingErrorTests: XCTestCase { TestEntity.self, from: entity_nonNullable_relationship_is_null )) { error in - XCTAssertEqual( - error as? ResourceObjectDecodingError, - ResourceObjectDecodingError( - subjectName: "required", - cause: .valueNotFound, - location: .relationships, - jsonAPIType: TestEntity.jsonType + let specialError = error as? ResourceObjectDecodingError + + XCTAssertNotNil(specialError) + + // later Linux versions of Swift will catch that the value is not + // a string rather than calling null "not found." The errors are both + // effective, so we check that one of the two is the result: + if specialError?.cause == .valueNotFound { + XCTAssertEqual( + specialError, + ResourceObjectDecodingError( + subjectName: "required", + cause: .valueNotFound, + location: .relationships, + jsonAPIType: TestEntity.jsonType + ) ) - ) - XCTAssertEqual( - (error as? ResourceObjectDecodingError)?.description, - "'required' relationship is not nullable but null was found." - ) + XCTAssertEqual( + specialError?.description, + "'required' relationship is not nullable but null was found." + ) + } else { + XCTAssertEqual( + specialError, + ResourceObjectDecodingError( + subjectName: "required", + cause: .typeMismatch(expectedTypeName: "Dictionary"), + location: .relationships, + jsonAPIType: TestEntity.jsonType + ) + ) + + XCTAssertEqual( + specialError?.description, + "'required' relationship is not a Dictionary as expected." + ) + } } } @@ -259,20 +283,44 @@ extension ResourceObjectDecodingErrorTests { TestEntity2.self, from: entity_nonNullable_attribute_is_null )) { error in - XCTAssertEqual( - error as? ResourceObjectDecodingError, - ResourceObjectDecodingError( - subjectName: "required", - cause: .valueNotFound, - location: .attributes, - jsonAPIType: TestEntity2.jsonType + let specialError = error as? ResourceObjectDecodingError + + XCTAssertNotNil(specialError) + + // later Linux versions of Swift will catch that the value is not + // a string rather than calling null "not found." The errors are both + // effective, so we check that one of the two is the result: + if specialError?.cause == .valueNotFound { + XCTAssertEqual( + specialError, + ResourceObjectDecodingError( + subjectName: "required", + cause: .valueNotFound, + location: .attributes, + jsonAPIType: TestEntity2.jsonType + ) ) - ) - XCTAssertEqual( - (error as? ResourceObjectDecodingError)?.description, - "'required' attribute is not nullable but null was found." - ) + XCTAssertEqual( + specialError?.description, + "'required' attribute is not nullable but null was found." + ) + } else { + XCTAssertEqual( + specialError, + ResourceObjectDecodingError( + subjectName: "required", + cause: .typeMismatch(expectedTypeName: "String"), + location: .attributes, + jsonAPIType: TestEntity2.jsonType + ) + ) + + XCTAssertEqual( + specialError?.description, + "'required' attribute is not a String as expected." + ) + } } } From 5e125abc5943924035dab28dfb5d0d032fd731ac Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:52:21 -0700 Subject: [PATCH 08/33] fix another test --- .../ResourceObjectDecodingErrorTests.swift | 48 ++++++++++++++----- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift index 3003dae..d8fcd0c 100644 --- a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift +++ b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift @@ -498,20 +498,44 @@ extension ResourceObjectDecodingErrorTests { TestEntity2.self, from: entity_type_is_null )) { error in - XCTAssertEqual( - error as? ResourceObjectDecodingError, - ResourceObjectDecodingError( - subjectName: "type", - cause: .valueNotFound, - location: .type, - jsonAPIType: TestEntity2.jsonType + let specialError = error as? ResourceObjectDecodingError + + XCTAssertNotNil(specialError) + + // later Linux versions of Swift will catch that the value is not + // a string rather than calling null "not found." The errors are both + // effective, so we check that one of the two is the result: + if specialError?.cause == .valueNotFound { + XCTAssertEqual( + specialError, + ResourceObjectDecodingError( + subjectName: "type", + cause: .valueNotFound, + location: .type, + jsonAPIType: TestEntity2.jsonType + ) ) - ) - XCTAssertEqual( - (error as? ResourceObjectDecodingError)?.description, - #"'type' (a.k.a. JSON:API type name) is not nullable but null was found."# - ) + XCTAssertEqual( + specialError?.description, + "'type' (a.k.a. JSON:API type name) is not nullable but null was found." + ) + } else { + XCTAssertEqual( + specialError, + ResourceObjectDecodingError( + subjectName: "type", + cause: .typeMismatch(expectedTypeName: "String"), + location: .type, + jsonAPIType: TestEntity2.jsonType + ) + ) + + XCTAssertEqual( + specialError?.description, + "'type' (a.k.a. JSON:API type name) is not a String as expected." + ) + } } } } From 9d0c320e3b327c3a2831a9623e7765b60aab9cb7 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 22:56:24 -0700 Subject: [PATCH 09/33] update linux swift images used for later versions of swift. --- .github/workflows/tests.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 00fc0fe..944a0a1 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -33,10 +33,9 @@ jobs: - swift:5.5-focal - swift:5.5-centos8 - swift:5.5-amazonlinux2 - - swift:5.6-xenial - swift:5.6-bionic - swift:5.6-focal - - swift:5.6-centos8 + - swift:5.6-centos7 - swift:5.6-amazonlinux2 container: ${{ matrix.image }} steps: From 6ccd8fd89183cf518e6721614204015ed88b2180 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 23:14:28 -0700 Subject: [PATCH 10/33] hopefully catch a stupid handling of null in linux decoding of json. --- Sources/JSONAPI/Document/DocumentDecodingError.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/JSONAPI/Document/DocumentDecodingError.swift b/Sources/JSONAPI/Document/DocumentDecodingError.swift index 2bcfa60..e31b816 100644 --- a/Sources/JSONAPI/Document/DocumentDecodingError.swift +++ b/Sources/JSONAPI/Document/DocumentDecodingError.swift @@ -33,6 +33,8 @@ public enum DocumentDecodingError: Swift.Error, Equatable { self = .primaryResourceMissing case .valueNotFound(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self: self = .primaryResourcesMissing + case .typeMismatch(_, let context) where context.debugDescription.hasSuffix("but found null instead."): + self = .primaryResourcesMissing default: return nil } From d94166074c38b384c3280e54baa44156b9cb615c Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 23:22:55 -0700 Subject: [PATCH 11/33] tweak test expectation --- .../Resource Object/ResourceObjectDecodingError.swift | 4 ++-- .../ResourceObject/ResourceObjectDecodingErrorTests.swift | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift b/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift index 72f0a2a..004e03c 100644 --- a/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift +++ b/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift @@ -137,7 +137,7 @@ extension ResourceObjectDecodingError: CustomStringConvertible { case .keyNotFound where subjectName == ResourceObjectDecodingError.entireObject: return "\(location) object is required and missing." case .keyNotFound where location == .type: - return "'type' (a.k.a. JSON:API type name) is required and missing." + return "'type' (a.k.a. the JSON:API type name) is required and missing." case .keyNotFound where location == .relationshipType: return "'\(subjectName)' relationship does not have a 'type'." case .keyNotFound where location == .relationshipId: @@ -145,7 +145,7 @@ extension ResourceObjectDecodingError: CustomStringConvertible { case .keyNotFound: return "'\(subjectName)' \(location.singular) is required and missing." case .valueNotFound where location == .type: - return "'\(location.singular)' (a.k.a. JSON:API type name) is not nullable but null was found." + return "'\(location.singular)' (a.k.a. the JSON:API type name) is not nullable but null was found." case .valueNotFound: return "'\(subjectName)' \(location.singular) is not nullable but null was found." case .typeMismatch(expectedTypeName: let expected) where location == .type: diff --git a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift index d8fcd0c..694acb9 100644 --- a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift +++ b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift @@ -488,7 +488,7 @@ extension ResourceObjectDecodingErrorTests { XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, - #"'type' (a.k.a. JSON:API type name) is required and missing."# + #"'type' (a.k.a. the JSON:API type name) is required and missing."# ) } } @@ -518,7 +518,7 @@ extension ResourceObjectDecodingErrorTests { XCTAssertEqual( specialError?.description, - "'type' (a.k.a. JSON:API type name) is not nullable but null was found." + "'type' (a.k.a. the JSON:API type name) is not nullable but null was found." ) } else { XCTAssertEqual( @@ -533,7 +533,7 @@ extension ResourceObjectDecodingErrorTests { XCTAssertEqual( specialError?.description, - "'type' (a.k.a. JSON:API type name) is not a String as expected." + "'type' (a.k.a. the JSON:API type name) is not a String as expected." ) } } From 86de52ffb87a4d4011d860b46cd3c4341c7a3f8d Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 23:31:09 -0700 Subject: [PATCH 12/33] ditch centos which had non-test-related error. fix type mismatch heuristic. --- .github/workflows/tests.yml | 1 - Sources/JSONAPI/Document/DocumentDecodingError.swift | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 944a0a1..7f5d35b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -35,7 +35,6 @@ jobs: - swift:5.5-amazonlinux2 - swift:5.6-bionic - swift:5.6-focal - - swift:5.6-centos7 - swift:5.6-amazonlinux2 container: ${{ matrix.image }} steps: diff --git a/Sources/JSONAPI/Document/DocumentDecodingError.swift b/Sources/JSONAPI/Document/DocumentDecodingError.swift index e31b816..f9994cf 100644 --- a/Sources/JSONAPI/Document/DocumentDecodingError.swift +++ b/Sources/JSONAPI/Document/DocumentDecodingError.swift @@ -33,7 +33,9 @@ public enum DocumentDecodingError: Swift.Error, Equatable { self = .primaryResourceMissing case .valueNotFound(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self: self = .primaryResourcesMissing - case .typeMismatch(_, let context) where context.debugDescription.hasSuffix("but found null instead."): + case .typeMismatch(let type, let context) where Location(context) == .data && type is AbstractResourceObject.Type && context.debugDescription.hasSuffix("but found null instead."): + self = .primaryResourceMissing + case .typeMismatch(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self && context.debugDescription.hasSuffix("but found null instead."): self = .primaryResourcesMissing default: return nil From 9e8c288a25580da0d3802fa8b2c6cc5c0692fc39 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 23:35:16 -0700 Subject: [PATCH 13/33] still trying to fix primary resource decoding error --- Sources/JSONAPI/Document/DocumentDecodingError.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/JSONAPI/Document/DocumentDecodingError.swift b/Sources/JSONAPI/Document/DocumentDecodingError.swift index f9994cf..34ff222 100644 --- a/Sources/JSONAPI/Document/DocumentDecodingError.swift +++ b/Sources/JSONAPI/Document/DocumentDecodingError.swift @@ -33,10 +33,10 @@ public enum DocumentDecodingError: Swift.Error, Equatable { self = .primaryResourceMissing case .valueNotFound(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self: self = .primaryResourcesMissing - case .typeMismatch(let type, let context) where Location(context) == .data && type is AbstractResourceObject.Type && context.debugDescription.hasSuffix("but found null instead."): - self = .primaryResourceMissing case .typeMismatch(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self && context.debugDescription.hasSuffix("but found null instead."): self = .primaryResourcesMissing + case .typeMismatch(_, let context) where Location(context) == .data && context.debugDescription.hasSuffix("but found null instead."): + self = .primaryResourceMissing default: return nil } From aec39fc010c6408f6c6e52db0bfaccb0787d07ec Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 23 Aug 2022 23:48:18 -0700 Subject: [PATCH 14/33] trying to determine when a primary resource error should be plural or not. --- Sources/JSONAPI/Document/DocumentDecodingError.swift | 5 ++++- Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Sources/JSONAPI/Document/DocumentDecodingError.swift b/Sources/JSONAPI/Document/DocumentDecodingError.swift index 34ff222..92e9ade 100644 --- a/Sources/JSONAPI/Document/DocumentDecodingError.swift +++ b/Sources/JSONAPI/Document/DocumentDecodingError.swift @@ -33,7 +33,7 @@ public enum DocumentDecodingError: Swift.Error, Equatable { self = .primaryResourceMissing case .valueNotFound(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self: self = .primaryResourcesMissing - case .typeMismatch(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self && context.debugDescription.hasSuffix("but found null instead."): + case .typeMismatch(let type, let context) where Location(context) == .data && type is _ArrayType.Type && context.debugDescription.hasSuffix("but found null instead."): self = .primaryResourcesMissing case .typeMismatch(_, let context) where Location(context) == .data && context.debugDescription.hasSuffix("but found null instead."): self = .primaryResourceMissing @@ -75,3 +75,6 @@ extension DocumentDecodingError: CustomStringConvertible { } } } + +private protocol _ArrayType {} +extension Array: _ArrayType {} diff --git a/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift b/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift index a10d45f..0100a07 100644 --- a/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift +++ b/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift @@ -53,7 +53,7 @@ final class DocumentDecodingErrorTests: XCTestCase { ) { error in guard let docError = error as? DocumentDecodingError, case .primaryResourcesMissing = docError else { - XCTFail("Expected primary resource missing error. Got \(error)") + XCTFail("Expected primary resources missing error. Got \(error)") return } From 4d75ff98fc6476ef8b98c16ba78a6f2a4cc6d085 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 13 Jan 2023 23:18:35 -0600 Subject: [PATCH 15/33] Update CI action versions --- .github/workflows/tests.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7f5d35b..1f3cf2e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -36,19 +36,20 @@ jobs: - swift:5.6-bionic - swift:5.6-focal - swift:5.6-amazonlinux2 + - swift:5.7-jammy container: ${{ matrix.image }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Run tests run: swift test --enable-test-discovery osx: runs-on: macOS-latest steps: - name: Select latest available Xcode - uses: maxim-lobanov/setup-xcode@v1.2.1 + uses: maxim-lobanov/setup-xcode@v1 with: { 'xcode-version': 'latest' } - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Run tests run: swift test --enable-test-discovery From df7d9d55f4d0692a60bb5f67f57ba07d893b86d0 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 13 Jan 2023 23:22:14 -0600 Subject: [PATCH 16/33] Update .github/workflows/tests.yml --- .github/workflows/tests.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1f3cf2e..e7cd4df 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -36,7 +36,6 @@ jobs: - swift:5.6-bionic - swift:5.6-focal - swift:5.6-amazonlinux2 - - swift:5.7-jammy container: ${{ matrix.image }} steps: - name: Checkout code From b9cb23d6235917a50a1386e06d39e67c0deffbda Mon Sep 17 00:00:00 2001 From: Vitalii Budnik Date: Wed, 20 Sep 2023 18:53:51 +0300 Subject: [PATCH 17/33] chore: allow mixing meta while merging Body.Data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ignore irrelevant generic types when merging Document.Body.Data. ### Reasoning I have a paginated request and response data has no meta and links, because it’s irrelevant for me. --- Sources/JSONAPI/Document/Document.swift | 11 ++++++----- Tests/JSONAPITests/Document/DocumentTests.swift | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/Sources/JSONAPI/Document/Document.swift b/Sources/JSONAPI/Document/Document.swift index da0a37f..b10a97f 100644 --- a/Sources/JSONAPI/Document/Document.swift +++ b/Sources/JSONAPI/Document/Document.swift @@ -261,7 +261,7 @@ extension Document { } extension Document.Body.Data where PrimaryResourceBody: ResourceBodyAppendable { - public func merging(_ other: Document.Body.Data, + public func merging(_ other: Document.Body.Data, combiningMetaWith metaMerge: (MetaType, MetaType) -> MetaType, combiningLinksWith linksMerge: (LinksType, LinksType) -> LinksType) -> Document.Body.Data { return Document.Body.Data(primary: primary.appending(other.primary), @@ -272,10 +272,11 @@ extension Document.Body.Data where PrimaryResourceBody: ResourceBodyAppendable { } extension Document.Body.Data where PrimaryResourceBody: ResourceBodyAppendable, MetaType == NoMetadata, LinksType == NoLinks { - public func merging(_ other: Document.Body.Data) -> Document.Body.Data { - return merging(other, - combiningMetaWith: { _, _ in .none }, - combiningLinksWith: { _, _ in .none }) + public func merging(_ other: Document.Body.Data) -> Document.Body.Data { + return Document.Body.Data(primary: primary.appending(other.primary), + includes: includes.appending(other.includes), + meta: meta, + links: links) } } diff --git a/Tests/JSONAPITests/Document/DocumentTests.swift b/Tests/JSONAPITests/Document/DocumentTests.swift index d6058ec..1acc297 100644 --- a/Tests/JSONAPITests/Document/DocumentTests.swift +++ b/Tests/JSONAPITests/Document/DocumentTests.swift @@ -1528,6 +1528,23 @@ extension DocumentTests { XCTAssertEqual(combined.primary.values, bodyData1.primary.values + bodyData2.primary.values) } + public func test_MergeBodyDataMixedMetaLinksErrorAndAPI(){ + let entity1 = Article(attributes: .none, relationships: .init(author: "2"), meta: .none, links: .none) + let entity2 = Article(attributes: .none, relationships: .init(author: "3"), meta: .none, links: .none) + + let bodyData1 = Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError>.Body.Data(primary: .init(resourceObjects: [entity1]), + includes: .none, + meta: .none, + links: .none) + let bodyData2 = Document, TestPageMetadata, TestLinks, NoIncludes, TestAPIDescription, GenericJSONAPIError>.Body.Data(primary: .init(resourceObjects: [entity2]), + includes: .none, + meta: .init(total: 5, limit: 2, offset: 2), + links: .init(link: .init(url: "one"), link2: .init(url: .init(), meta: .init(hello: "world")))) + let combined = bodyData1.merging(bodyData2) + + XCTAssertEqual(combined.primary.values, bodyData1.primary.values + bodyData2.primary.values) + } + public func test_MergeBodyDataWithMergeFunctions() { let article1 = Article(attributes: .none, relationships: .init(author: "2"), meta: .none, links: .none) let author1 = Author(id: "2", attributes: .none, relationships: .none, meta: .none, links: .none) From 7f326df678d9b5f6d421488c4bd37da9d2d42c8b Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 1 Mar 2024 13:36:00 -0600 Subject: [PATCH 18/33] keep the metadata and links for the merged-in document body if the merged-into document body has no metadata or links. --- Sources/JSONAPI/Document/Document.swift | 10 +++++----- Tests/JSONAPITests/Document/DocumentTests.swift | 2 ++ 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Sources/JSONAPI/Document/Document.swift b/Sources/JSONAPI/Document/Document.swift index b10a97f..3673493 100644 --- a/Sources/JSONAPI/Document/Document.swift +++ b/Sources/JSONAPI/Document/Document.swift @@ -272,11 +272,11 @@ extension Document.Body.Data where PrimaryResourceBody: ResourceBodyAppendable { } extension Document.Body.Data where PrimaryResourceBody: ResourceBodyAppendable, MetaType == NoMetadata, LinksType == NoLinks { - public func merging(_ other: Document.Body.Data) -> Document.Body.Data { - return Document.Body.Data(primary: primary.appending(other.primary), - includes: includes.appending(other.includes), - meta: meta, - links: links) + public func merging(_ other: Document.Body.Data) -> Document.Body.Data { + return .init(primary: primary.appending(other.primary), + includes: includes.appending(other.includes), + meta: other.meta, + links: other.links) } } diff --git a/Tests/JSONAPITests/Document/DocumentTests.swift b/Tests/JSONAPITests/Document/DocumentTests.swift index 1acc297..559a257 100644 --- a/Tests/JSONAPITests/Document/DocumentTests.swift +++ b/Tests/JSONAPITests/Document/DocumentTests.swift @@ -1543,6 +1543,8 @@ extension DocumentTests { let combined = bodyData1.merging(bodyData2) XCTAssertEqual(combined.primary.values, bodyData1.primary.values + bodyData2.primary.values) + XCTAssertEqual(combined.meta, bodyData2.meta) + XCTAssertEqual(combined.links, bodyData2.links) } public func test_MergeBodyDataWithMergeFunctions() { From f1945d29663c828f5916756b857321ddd3c2727b Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Wed, 27 Mar 2024 13:59:18 -0500 Subject: [PATCH 19/33] add support for 14 includes --- Package.resolved | 4 +- Package.swift | 2 +- Sources/JSONAPI/Document/Includes.swift | 8 ++ .../Resource/Poly+PrimaryResource.swift | 35 ++++++ .../JSONAPITests/Includes/IncludeTests.swift | 36 +++++++ .../Includes/stubs/IncludeStubs.swift | 102 ++++++++++++++++++ 6 files changed, 184 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 8a582ff..6540547 100644 --- a/Package.resolved +++ b/Package.resolved @@ -6,8 +6,8 @@ "repositoryURL": "https://github.com/mattpolzin/Poly.git", "state": { "branch": null, - "revision": "c108e9e0a2904134719b082f6c18d64406afc6db", - "version": "2.6.0" + "revision": "fb90ab22a09fe32e8cb152f7dea344df82a59d53", + "version": "2.7.0" } } ] diff --git a/Package.swift b/Package.swift index e7a0e51..f6a29f7 100644 --- a/Package.swift +++ b/Package.swift @@ -17,7 +17,7 @@ let package = Package( targets: ["JSONAPITesting"]) ], dependencies: [ - .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.6.0")), + .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.7.0")), ], targets: [ .target( diff --git a/Sources/JSONAPI/Document/Includes.swift b/Sources/JSONAPI/Document/Includes.swift index 30634ae..9f5b1bd 100644 --- a/Sources/JSONAPI/Document/Includes.swift +++ b/Sources/JSONAPI/Document/Includes.swift @@ -222,6 +222,14 @@ extension Includes where I: _Poly13 { } } +// MARK: - 14 includes +public typealias Include14 = Poly14 +extension Includes where I: _Poly14 { + public subscript(_ lookup: I.N.Type) -> [I.N] { + return values.compactMap(\.n) + } +} + // MARK: - DecodingError public struct IncludesDecodingError: Swift.Error, Equatable { public let error: Swift.Error diff --git a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift index 0dab925..c341302 100644 --- a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift +++ b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift @@ -226,3 +226,38 @@ J: CodablePolyWrapped, K: CodablePolyWrapped, L: CodablePolyWrapped, M: CodablePolyWrapped {} + +// MARK: - 14 types +extension Poly14: EncodablePrimaryResource, OptionalEncodablePrimaryResource +where +A: EncodablePolyWrapped, +B: EncodablePolyWrapped, +C: EncodablePolyWrapped, +D: EncodablePolyWrapped, +E: EncodablePolyWrapped, +F: EncodablePolyWrapped, +G: EncodablePolyWrapped, +H: EncodablePolyWrapped, +I: EncodablePolyWrapped, +J: EncodablePolyWrapped, +K: EncodablePolyWrapped, +L: EncodablePolyWrapped, +M: EncodablePolyWrapped, +N: EncodablePolyWrapped {} + +extension Poly14: CodablePrimaryResource, OptionalCodablePrimaryResource +where +A: CodablePolyWrapped, +B: CodablePolyWrapped, +C: CodablePolyWrapped, +D: CodablePolyWrapped, +E: CodablePolyWrapped, +F: CodablePolyWrapped, +G: CodablePolyWrapped, +H: CodablePolyWrapped, +I: CodablePolyWrapped, +J: CodablePolyWrapped, +K: CodablePolyWrapped, +L: CodablePolyWrapped, +M: CodablePolyWrapped, +N: CodablePolyWrapped {} diff --git a/Tests/JSONAPITests/Includes/IncludeTests.swift b/Tests/JSONAPITests/Includes/IncludeTests.swift index e0a44a4..73b1922 100644 --- a/Tests/JSONAPITests/Includes/IncludeTests.swift +++ b/Tests/JSONAPITests/Includes/IncludeTests.swift @@ -266,6 +266,31 @@ class IncludedTests: XCTestCase { test_DecodeEncodeEquality(type: Includes>.self, data: thirteen_different_type_includes) } + + func test_FourteenDifferentIncludes() { + let includes = decoded(type: Includes>.self, + data: fourteen_different_type_includes) + + XCTAssertEqual(includes[TestEntity.self].count, 1) + XCTAssertEqual(includes[TestEntity2.self].count, 1) + XCTAssertEqual(includes[TestEntity3.self].count, 1) + XCTAssertEqual(includes[TestEntity4.self].count, 1) + XCTAssertEqual(includes[TestEntity5.self].count, 1) + XCTAssertEqual(includes[TestEntity6.self].count, 1) + XCTAssertEqual(includes[TestEntity7.self].count, 1) + XCTAssertEqual(includes[TestEntity8.self].count, 1) + XCTAssertEqual(includes[TestEntity9.self].count, 1) + XCTAssertEqual(includes[TestEntity10.self].count, 1) + XCTAssertEqual(includes[TestEntity11.self].count, 1) + XCTAssertEqual(includes[TestEntity12.self].count, 1) + XCTAssertEqual(includes[TestEntity13.self].count, 1) + XCTAssertEqual(includes[TestEntity14.self].count, 1) + } + + func test_FourteenDifferentIncludes_encode() { + test_DecodeEncodeEquality(type: Includes>.self, + data: fourteen_different_type_includes) + } } // MARK: - Appending @@ -605,4 +630,15 @@ extension IncludedTests { } typealias TestEntity13 = BasicEntity + + enum TestEntityType14: ResourceObjectDescription { + + typealias Attributes = NoAttributes + + public static var jsonType: String { return "test_entity14" } + + typealias Relationships = NoRelationships + } + + typealias TestEntity14 = BasicEntity } diff --git a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift index 2cfd3fa..7d23d22 100644 --- a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift +++ b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift @@ -877,6 +877,108 @@ let thirteen_different_type_includes = """ ] """.data(using: .utf8)! +let fourteen_different_type_includes = """ +[ + { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF", + "attributes": { + "foo": "Hello", + "bar": 123 + } + }, + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333", + "attributes": { + "foo": "World", + "bar": 456 + }, + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + } + } + }, + { + "type": "test_entity3", + "id": "11223B69-4DF1-467F-B52E-B0C9E44FC443", + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + }, + "entity2": { + "data": [ + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333" + } + ] + } + } + }, + { + "type": "test_entity6", + "id": "11113B69-4DF1-467F-B52E-B0C9E44FC444", + "relationships": { + "entity4": { + "data": { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + } + } + } + }, + { + "type": "test_entity5", + "id": "A24B3B69-4DF1-467F-B52E-B0C9E44F436A" + }, + { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity7", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity8", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F266F" + }, + { + "type": "test_entity9", + "id": "364B3B69-4DF1-218F-B52E-B0C9E44F2661" + }, + { + "type": "test_entity10", + "id": "264B3B69-4DF1-212F-B52E-B0C9E44F2660" + }, + { + "type": "test_entity11", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C0B" + }, + { + "type": "test_entity12", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C00" + }, + { + "type": "test_entity13", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C01" + }, + { + "type": "test_entity14", + "id": "264B3B69-4DF3-312F-B32E-A0C9E44F26C01" + } +] +""".data(using: .utf8)! + + let three_includes_one_missing_attributes = """ [ { From 9b919b68673bc2b755d6033748de22a8035753ff Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Wed, 27 Mar 2024 17:22:04 -0500 Subject: [PATCH 20/33] support for Include15 type --- Package.resolved | 4 +- Package.swift | 2 +- Sources/JSONAPI/Document/Includes.swift | 8 ++ .../Resource/Poly+PrimaryResource.swift | 37 ++++++ .../JSONAPITests/Includes/IncludeTests.swift | 37 ++++++ .../Includes/stubs/IncludeStubs.swift | 105 ++++++++++++++++++ 6 files changed, 190 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 6540547..f7c521e 100644 --- a/Package.resolved +++ b/Package.resolved @@ -6,8 +6,8 @@ "repositoryURL": "https://github.com/mattpolzin/Poly.git", "state": { "branch": null, - "revision": "fb90ab22a09fe32e8cb152f7dea344df82a59d53", - "version": "2.7.0" + "revision": "99e2e8b575620369be52fe348c0dd72028e3674c", + "version": "2.8.0" } } ] diff --git a/Package.swift b/Package.swift index f6a29f7..81b978c 100644 --- a/Package.swift +++ b/Package.swift @@ -17,7 +17,7 @@ let package = Package( targets: ["JSONAPITesting"]) ], dependencies: [ - .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.7.0")), + .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.8.0")), ], targets: [ .target( diff --git a/Sources/JSONAPI/Document/Includes.swift b/Sources/JSONAPI/Document/Includes.swift index 9f5b1bd..b76225e 100644 --- a/Sources/JSONAPI/Document/Includes.swift +++ b/Sources/JSONAPI/Document/Includes.swift @@ -230,6 +230,14 @@ extension Includes where I: _Poly14 { } } +// MARK: - 15 includes +public typealias Include15 = Poly15 +extension Includes where I: _Poly15 { + public subscript(_ lookup: I.O.Type) -> [I.O] { + return values.compactMap(\.o) + } +} + // MARK: - DecodingError public struct IncludesDecodingError: Swift.Error, Equatable { public let error: Swift.Error diff --git a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift index c341302..1443610 100644 --- a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift +++ b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift @@ -261,3 +261,40 @@ K: CodablePolyWrapped, L: CodablePolyWrapped, M: CodablePolyWrapped, N: CodablePolyWrapped {} + +// MARK: - 15 types +extension Poly15: EncodablePrimaryResource, OptionalEncodablePrimaryResource +where +A: EncodablePolyWrapped, +B: EncodablePolyWrapped, +C: EncodablePolyWrapped, +D: EncodablePolyWrapped, +E: EncodablePolyWrapped, +F: EncodablePolyWrapped, +G: EncodablePolyWrapped, +H: EncodablePolyWrapped, +I: EncodablePolyWrapped, +J: EncodablePolyWrapped, +K: EncodablePolyWrapped, +L: EncodablePolyWrapped, +M: EncodablePolyWrapped, +N: EncodablePolyWrapped, +O: EncodablePolyWrapped {} + +extension Poly15: CodablePrimaryResource, OptionalCodablePrimaryResource +where +A: CodablePolyWrapped, +B: CodablePolyWrapped, +C: CodablePolyWrapped, +D: CodablePolyWrapped, +E: CodablePolyWrapped, +F: CodablePolyWrapped, +G: CodablePolyWrapped, +H: CodablePolyWrapped, +I: CodablePolyWrapped, +J: CodablePolyWrapped, +K: CodablePolyWrapped, +L: CodablePolyWrapped, +M: CodablePolyWrapped, +N: CodablePolyWrapped, +O: CodablePolyWrapped {} diff --git a/Tests/JSONAPITests/Includes/IncludeTests.swift b/Tests/JSONAPITests/Includes/IncludeTests.swift index 73b1922..088fbe2 100644 --- a/Tests/JSONAPITests/Includes/IncludeTests.swift +++ b/Tests/JSONAPITests/Includes/IncludeTests.swift @@ -291,6 +291,32 @@ class IncludedTests: XCTestCase { test_DecodeEncodeEquality(type: Includes>.self, data: fourteen_different_type_includes) } + + func test_FifteenDifferentIncludes() { + let includes = decoded(type: Includes>.self, + data: fifteen_different_type_includes) + + XCTAssertEqual(includes[TestEntity.self].count, 1) + XCTAssertEqual(includes[TestEntity2.self].count, 1) + XCTAssertEqual(includes[TestEntity3.self].count, 1) + XCTAssertEqual(includes[TestEntity4.self].count, 1) + XCTAssertEqual(includes[TestEntity5.self].count, 1) + XCTAssertEqual(includes[TestEntity6.self].count, 1) + XCTAssertEqual(includes[TestEntity7.self].count, 1) + XCTAssertEqual(includes[TestEntity8.self].count, 1) + XCTAssertEqual(includes[TestEntity9.self].count, 1) + XCTAssertEqual(includes[TestEntity10.self].count, 1) + XCTAssertEqual(includes[TestEntity11.self].count, 1) + XCTAssertEqual(includes[TestEntity12.self].count, 1) + XCTAssertEqual(includes[TestEntity13.self].count, 1) + XCTAssertEqual(includes[TestEntity14.self].count, 1) + XCTAssertEqual(includes[TestEntity15.self].count, 1) + } + + func test_FifteenDifferentIncludes_encode() { + test_DecodeEncodeEquality(type: Includes>.self, + data: fifteen_different_type_includes) + } } // MARK: - Appending @@ -641,4 +667,15 @@ extension IncludedTests { } typealias TestEntity14 = BasicEntity + + enum TestEntityType15: ResourceObjectDescription { + + typealias Attributes = NoAttributes + + public static var jsonType: String { return "test_entity15" } + + typealias Relationships = NoRelationships + } + + typealias TestEntity15 = BasicEntity } diff --git a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift index 7d23d22..df47120 100644 --- a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift +++ b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift @@ -978,6 +978,111 @@ let fourteen_different_type_includes = """ ] """.data(using: .utf8)! +let fifteen_different_type_includes = """ +[ + { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF", + "attributes": { + "foo": "Hello", + "bar": 123 + } + }, + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333", + "attributes": { + "foo": "World", + "bar": 456 + }, + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + } + } + }, + { + "type": "test_entity3", + "id": "11223B69-4DF1-467F-B52E-B0C9E44FC443", + "relationships": { + "entity1": { + "data": { + "type": "test_entity1", + "id": "2DF03B69-4B0A-467F-B52E-B0C9E44FCECF" + } + }, + "entity2": { + "data": [ + { + "type": "test_entity2", + "id": "90F03B69-4DF1-467F-B52E-B0C9E44FC333" + } + ] + } + } + }, + { + "type": "test_entity6", + "id": "11113B69-4DF1-467F-B52E-B0C9E44FC444", + "relationships": { + "entity4": { + "data": { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + } + } + } + }, + { + "type": "test_entity5", + "id": "A24B3B69-4DF1-467F-B52E-B0C9E44F436A" + }, + { + "type": "test_entity4", + "id": "364B3B69-4DF1-467F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity7", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F666E" + }, + { + "type": "test_entity8", + "id": "364B3B69-4DF1-222F-B52E-B0C9E44F266F" + }, + { + "type": "test_entity9", + "id": "364B3B69-4DF1-218F-B52E-B0C9E44F2661" + }, + { + "type": "test_entity10", + "id": "264B3B69-4DF1-212F-B52E-B0C9E44F2660" + }, + { + "type": "test_entity11", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C0B" + }, + { + "type": "test_entity12", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C00" + }, + { + "type": "test_entity13", + "id": "264B3B69-4DF3-212F-B32E-A0C9E44F26C01" + }, + { + "type": "test_entity14", + "id": "264B3B69-4DF3-312F-B32E-A0C9E44F26C01" + }, + { + "type": "test_entity15", + "id": "264B3B69-4DF3-312A-B32E-A0C9E44F26C01" + } +] +""".data(using: .utf8)! + let three_includes_one_missing_attributes = """ [ From 83cf5bba875b44e927b11ae47938f3a4e88666a3 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 30 Apr 2024 09:31:36 -0500 Subject: [PATCH 21/33] allow optional metadata to be omitted as well as nulled out. --- Sources/JSONAPI/Resource/Relationship.swift | 3 --- .../Resource Object/ResourceObject.swift | 12 +++++++++- .../ResourceObject/ResourceObjectTests.swift | 22 +++++++++++++++++-- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/Sources/JSONAPI/Resource/Relationship.swift b/Sources/JSONAPI/Resource/Relationship.swift index fc03c4e..4a2c3fa 100644 --- a/Sources/JSONAPI/Resource/Relationship.swift +++ b/Sources/JSONAPI/Resource/Relationship.swift @@ -263,9 +263,6 @@ extension MetaRelationship: Codable { } } -fileprivate protocol _Optional {} -extension Optional: _Optional {} - extension ToOneRelationship: Codable where Identifiable.ID: OptionalId { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ResourceLinkageCodingKeys.self) diff --git a/Sources/JSONAPI/Resource/Resource Object/ResourceObject.swift b/Sources/JSONAPI/Resource/Resource Object/ResourceObject.swift index 77d367e..1b4308b 100644 --- a/Sources/JSONAPI/Resource/Resource Object/ResourceObject.swift +++ b/Sources/JSONAPI/Resource/Resource Object/ResourceObject.swift @@ -447,7 +447,17 @@ public extension ResourceObject { ) } - meta = try (NoMetadata() as? MetaType) ?? container.decode(MetaType.self, forKey: .meta) + do { + meta = try (NoMetadata() as? MetaType) ?? container.decode(MetaType.self, forKey: .meta) + } catch let decodingError as DecodingError { + let anyNil: Any? = nil + + guard case .keyNotFound = decodingError, + let omittedMeta = anyNil as? MetaType else { + throw decodingError + } + meta = omittedMeta + } links = try (NoLinks() as? LinksType) ?? container.decode(LinksType.self, forKey: .links) } diff --git a/Tests/JSONAPITests/ResourceObject/ResourceObjectTests.swift b/Tests/JSONAPITests/ResourceObject/ResourceObjectTests.swift index d492b18..77a75c7 100644 --- a/Tests/JSONAPITests/ResourceObject/ResourceObjectTests.swift +++ b/Tests/JSONAPITests/ResourceObject/ResourceObjectTests.swift @@ -151,6 +151,11 @@ extension ResourceObjectTests { data: entity_no_relationships_no_attributes) } + func test_EntityNoMetaDecodesAsOptionalMeta() { + let _ = decoded(type: TestEntityOptionalMeta.self, + data: entity_no_relationships_no_attributes) + } + func test_EntityNoRelationshipsSomeAttributes() { let entity = decoded(type: TestEntity5.self, data: entity_no_relationships_some_attributes) @@ -861,13 +866,13 @@ extension ResourceObjectTests { public struct Relationships: JSONAPI.Relationships { public init() { - optionalMeta = nil + optionalMeta = nil optionalOne = nil optionalNullableOne = nil optionalMany = nil } - let optionalMeta: MetaRelationship? + let optionalMeta: MetaRelationship? let optionalOne: ToOneRelationship? @@ -879,6 +884,19 @@ extension ResourceObjectTests { typealias TestEntity12 = BasicEntity + enum TestEntityOptionalMetaType: JSONAPI.ResourceObjectDescription { + public static var jsonType: String { return "test_entities" } + + typealias Attributes = NoAttributes + typealias Relationships = NoRelationships + } + + struct UnimportantMeta: JSONAPI.Meta { + let property1: String + } + + typealias TestEntityOptionalMeta = JSONAPI.ResourceObject + enum UnidentifiedTestEntityType: ResourceObjectDescription { public static var jsonType: String { return "unidentified_test_entities" } From 457ac3df7557bdb87d820d0efc3a4c1776363860 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 30 Apr 2024 11:10:33 -0500 Subject: [PATCH 22/33] fix test for latest MacOS Swift versions --- .../SparseFields/SparseFieldEncoderTests.swift | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Tests/JSONAPITests/SparseFields/SparseFieldEncoderTests.swift b/Tests/JSONAPITests/SparseFields/SparseFieldEncoderTests.swift index 9d5bba5..2625989 100644 --- a/Tests/JSONAPITests/SparseFields/SparseFieldEncoderTests.swift +++ b/Tests/JSONAPITests/SparseFields/SparseFieldEncoderTests.swift @@ -43,13 +43,9 @@ class SparseFieldEncoderTests: XCTestCase { XCTAssertEqual(allThingsOnDeserialized["bool"] as? Bool, true) XCTAssertEqual(allThingsOnDeserialized["double"] as? Double, 10.5) XCTAssertEqual(allThingsOnDeserialized["string"] as? String, "hello") - #if os(Linux) - // There's some bug with Linux where it won't case the value to a float. - // It does exist and it is == 1.2 + // For latest versions of MacOS and all versions of Linux, floats + // decode as doubles. XCTAssertEqual(allThingsOnDeserialized["float"] as? Double, 1.2) - #else - XCTAssertEqual(allThingsOnDeserialized["float"] as? Float, 1.2) - #endif XCTAssertEqual(allThingsOnDeserialized["int"] as? Int, 3) XCTAssertEqual(allThingsOnDeserialized["int8"] as? Int8, 4) XCTAssertEqual(allThingsOnDeserialized["int16"] as? Int16, 5) From 6f8e133d7d9c43c7a6d5a87b1a978dc2d014599f Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 30 Apr 2024 11:26:41 -0500 Subject: [PATCH 23/33] Fix decoding error support for newer MacOS Swift versions --- Sources/JSONAPI/Document/DocumentDecodingError.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/JSONAPI/Document/DocumentDecodingError.swift b/Sources/JSONAPI/Document/DocumentDecodingError.swift index 92e9ade..8a96054 100644 --- a/Sources/JSONAPI/Document/DocumentDecodingError.swift +++ b/Sources/JSONAPI/Document/DocumentDecodingError.swift @@ -33,6 +33,10 @@ public enum DocumentDecodingError: Swift.Error, Equatable { self = .primaryResourceMissing case .valueNotFound(let type, let context) where Location(context) == .data && type == UnkeyedDecodingContainer.self: self = .primaryResourcesMissing + case .valueNotFound(let type, let context) where Location(context) == .data && type is _ArrayType.Type && context.debugDescription.hasSuffix("found null value instead"): + self = .primaryResourcesMissing + case .valueNotFound(_, let context) where Location(context) == .data && context.debugDescription.hasSuffix("found null value instead"): + self = .primaryResourceMissing case .typeMismatch(let type, let context) where Location(context) == .data && type is _ArrayType.Type && context.debugDescription.hasSuffix("but found null instead."): self = .primaryResourcesMissing case .typeMismatch(_, let context) where Location(context) == .data && context.debugDescription.hasSuffix("but found null instead."): From ff0495dacb8afdf64418b60af127a7838196afe4 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 21 Apr 2025 10:02:13 -0500 Subject: [PATCH 24/33] Add test that shows a custom generic included type of resource --- .../JSONAPITests/Includes/IncludeTests.swift | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Tests/JSONAPITests/Includes/IncludeTests.swift b/Tests/JSONAPITests/Includes/IncludeTests.swift index 088fbe2..e4a24c5 100644 --- a/Tests/JSONAPITests/Includes/IncludeTests.swift +++ b/Tests/JSONAPITests/Includes/IncludeTests.swift @@ -72,6 +72,16 @@ class IncludedTests: XCTestCase { data: three_different_type_includes) } + func test_OneKnownAndTwoGenericIncludes() { + let includes = decoded(type: Includes>.self, + data: three_different_type_includes) + + XCTAssertEqual(includes[TestEntity.self].count, 1) + XCTAssertEqual(includes[TestEntityOther.self].count, 2) + XCTAssert(includes[TestEntityOther.self].contains { $0.type == "test_entity2"}) + XCTAssert(includes[TestEntityOther.self].contains { $0.type == "test_entity4"}) + } + func test_FourDifferentIncludes() { let includes = decoded(type: Includes>.self, data: four_different_type_includes) @@ -678,4 +688,50 @@ extension IncludedTests { } typealias TestEntity15 = BasicEntity + + enum TestEntityTypeOther: ResourceObjectProxyDescription { + public static var jsonType: String { return "_generic" } + + typealias Attributes = NoAttributes + typealias Relationships = NoRelationships + } + + struct TestEntityOther: ResourceObjectProxy, Codable { + typealias Description = TestEntityTypeOther + typealias EntityRawIdType = String + + public let type : String + public let id : JSONAPI.Id + + public let attributes = NoAttributes() + public let relationships = NoRelationships() + + enum CodingKeys: CodingKey { + case id + case type + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + let type: String + do { + type = try container.decode(String.self, forKey: .type) + } catch let error as DecodingError { + throw ResourceObjectDecodingError(error, jsonAPIType: Self.jsonType) + ?? error + } + + id = .init(rawValue: try container.decode(String.self, forKey: .id)) + self.type = type + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(type, forKey: .type) + + try container.encode(id, forKey: .id) + } + } } From 9017bc0e00ad8834b48be30b6813703383da5246 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 21 Apr 2025 10:07:50 -0500 Subject: [PATCH 25/33] remove unmaintained old Swift image variants --- .github/workflows/tests.yml | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e7cd4df..d6a87ee 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,29 +13,19 @@ jobs: fail-fast: false matrix: image: - - swift:5.2-xenial - - swift:5.2-bionic - swift:5.2-focal - swift:5.2-centos8 - - swift:5.2-amazonlinux2 - - swift:5.3-xenial - - swift:5.3-bionic - swift:5.3-focal - swift:5.3-centos8 - - swift:5.3-amazonlinux2 - - swift:5.4-xenial - - swift:5.4-bionic - swift:5.4-focal - swift:5.4-centos8 - - swift:5.4-amazonlinux2 - - swift:5.5-xenial - - swift:5.5-bionic - swift:5.5-focal - swift:5.5-centos8 - - swift:5.5-amazonlinux2 - - swift:5.6-bionic - swift:5.6-focal - - swift:5.6-amazonlinux2 + - swift:5.7-focal + - swift:5.8-focal + - swift:5.9-focal + - swift:5.10-focal container: ${{ matrix.image }} steps: - name: Checkout code From 93981efca07b74749f92f6a865ebca82cbc53161 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 21 Apr 2025 10:10:16 -0500 Subject: [PATCH 26/33] comment out versions of Linux Swift that have slightly different error messages so tests are not currently passing --- .github/workflows/tests.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index d6a87ee..9644cf8 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -22,10 +22,10 @@ jobs: - swift:5.5-focal - swift:5.5-centos8 - swift:5.6-focal - - swift:5.7-focal - - swift:5.8-focal - - swift:5.9-focal - - swift:5.10-focal +# - swift:5.7-focal +# - swift:5.8-focal +# - swift:5.9-focal +# - swift:5.10-focal container: ${{ matrix.image }} steps: - name: Checkout code From 8cea47ba6cf0d08cf033c357ec0f6128dc0e57f1 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 28 Apr 2025 09:27:43 -0500 Subject: [PATCH 27/33] switch from google colab examples to markdown --- README.md | 24 +-- documentation/examples/basic-example.md | 174 +++++++++++++++ .../{ => examples}/client-server-example.md | 0 documentation/examples/compound-example.md | 134 ++++++++++++ .../examples/custom-errors-example.md | 153 +++++++++++++ documentation/examples/metadata-example.md | 129 +++++++++++ documentation/examples/patch-example.md | 157 ++++++++++++++ .../examples/resource-storage-example.md | 204 ++++++++++++++++++ .../examples/serverside-get-example.md | 179 +++++++++++++++ .../examples/serverside-post-example.md | 152 +++++++++++++ 10 files changed, 1293 insertions(+), 13 deletions(-) create mode 100644 documentation/examples/basic-example.md rename documentation/{ => examples}/client-server-example.md (100%) create mode 100644 documentation/examples/compound-example.md create mode 100644 documentation/examples/custom-errors-example.md create mode 100644 documentation/examples/metadata-example.md create mode 100644 documentation/examples/patch-example.md create mode 100644 documentation/examples/resource-storage-example.md create mode 100644 documentation/examples/serverside-get-example.md create mode 100644 documentation/examples/serverside-post-example.md diff --git a/README.md b/README.md index c42c9d7..3fe2993 100644 --- a/README.md +++ b/README.md @@ -7,22 +7,20 @@ See the JSON API Spec here: https://jsonapi.org/format/ ## Quick Start -:warning: The following Google Colab examples have correct code, but from time to time the Google Colab Swift compiler may be buggy and claim it cannot build the JSONAPI library. - ### 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) -- [Custom Errors Example](https://colab.research.google.com/drive/1TIv6STzlHrkTf_-9Eu8sv8NoaxhZcFZH) -- [PATCH Example](https://colab.research.google.com/drive/16KY-0BoLQKiSUh9G7nYmHzB8b2vhXA2U) -- [Resource Storage Example](https://colab.research.google.com/drive/196eCnBlf2xz8pT4lW--ur6eWSVAjpF6b?usp=sharing) (using [JSONAPI-ResourceStorage](#jsonapi-resourcestorage)) +- [Basic Example](./documentation/examples/basic-example.md) +- [Compound Example](./documentation/examples/compound-example.md) +- [Metadata Example](./documentation/examples/metadata-example.md) +- [Custom Errors Example](./documentation/examples/custom-errors-example.md) +- [PATCH Example](./documentation/examples/patch-example.md) +- [Resource Storage Example](./documentation/examples/resource-storage-example.md) (using [JSONAPI-ResourceStorage](#jsonapi-resourcestorage)) ### Serverside -- [GET Example](https://colab.research.google.com/drive/1krbhzSfz8mwkBTQQnKUZJLEtYsJKSfYX) -- [POST Example](https://colab.research.google.com/drive/1z3n70LwRY7vLIgbsMghvnfHA67QiuqpQ) +- [GET Example](./documentation/examples/serverside-get-example.md) +- [POST Example](./documentation/examples/serverside-post-example.md) ### Client+Server -This library works well when used by both the server responsible for serialization and the client responsible for deserialization. Check out the [example](./documentation/client-server-example.md). +This library works well when used by both the server responsible for serialization and the client responsible for deserialization. Check out the [example](./documentation/examples/client-server-example.md). ## Table of Contents - JSONAPI @@ -34,7 +32,7 @@ This library works well when used by both the server responsible for serializati - [CocoaPods](#cocoapods) - [Running the Playground](#running-the-playground) - [Project Status](./documentation/project-status.md) - - [Server & Client Example](./documentation/client-server-example.md) + - [Server & Client Example](./documentation/examples/client-server-example.md) - [Usage](./documentation/usage.md) - [JSONAPI+Testing](#jsonapitesting) - [Literal Expressibility](#literal-expressibility) @@ -91,7 +89,7 @@ Note that Playground support for importing non-system Frameworks is still a bit ## Deeper Dive - [Project Status](./documentation/project-status.md) -- [Server & Client Example](./documentation/client-server-example.md) +- [Server & Client Example](./documentation/examples/client-server-example.md) - [Usage Documentation](./documentation/usage.md) # JSONAPI+Testing diff --git a/documentation/examples/basic-example.md b/documentation/examples/basic-example.md new file mode 100644 index 0000000..2b1e9fb --- /dev/null +++ b/documentation/examples/basic-example.md @@ -0,0 +1,174 @@ + +# JSONAPI Basic Example + +We are about to walk through a basic example to show how easy it is to set up a +simple model. Information on creating models that take advantage of more of the +features from the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +The `JSONAPI` framework relies heavily on generic types so the first step will +be to alias away some of the JSON:API features we do not need for our simple +example. + +```swift +/// Our Resource objects will not have any metadata or links and they will be identified by Strings. +typealias Resource = JSONAPI.ResourceObject + +/// Our JSON:API Documents will similarly have no metadata or links associated with them. Additionally, there will be no included resources. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> + +typealias BatchDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> +``` + +The next step is to create `ResourceObjectDescriptions` and `ResourceObjects`. +For our simple example, let's create a `Person` and a `Dog`. + +```swift +struct PersonDescription: ResourceObjectDescription { + // by common convention, we will use the plural form + // of the noun as the JSON:API "type" + static let jsonType: String = "people" + + struct Attributes: JSONAPI.Attributes { + let firstName: Attribute + let lastName: Attribute + + // we mark this attribute as "nullable" because the user can choose + // not to specify an age if they would like to. + let age: Attribute + } + + struct Relationships: JSONAPI.Relationships { + // we will define "Dog" next + let pets: ToManyRelationship + } +} + +// this typealias is optional, but it makes working with resource objects much +// more user friendly. +typealias Person = Resource + +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + // we could relate dogs back to their owners, but for the sake of this example + // we will instead show how you would create a resource with no relationships. + typealias Relationships = NoRelationships +} + +typealias Dog = Resource +``` + +At this point we have two objects that can decode JSON:API responses. To +illustrate we can mock up a dog response and parse it. + +```swift +// snag Foundation for JSONDecoder +import Foundation + +let mockBatchDogResponse = +""" +{ + "data": [ + { + "type": "dogs", + "id": "123", + "attributes": { + "name": "Sparky" + } + }, + { + "type": "dogs", + "id": "456", + "attributes": { + "name": "Charlie Dog" + } + } + ] +} +""".data(using: .utf8)! + +let decoder = JSONDecoder() + +let dogsDocument = try! decoder.decode(BatchDocument.self, from: mockBatchDogResponse) + +let dogs = dogsDocument.body.primaryResource!.values + +print("dogs parsed: \(dogs.count ?? 0)") +``` + +To illustrate `ResourceObject` property access, we can loop over the dogs and +print their names. + +```swift +for dog in dogs { + print(dog.name) +} +``` + +Now let's parse a mocked `Person` response. + +```swift +let mockSinglePersonResponse = +""" +{ + "data": { + "type": "people", + "id": "88223", + "attributes": { + "first_name": "Lisa", + "last_name": "Offenbrook", + "age": null + }, + "relationships": { + "pets": { + "data": [ + { + "type": "dogs", + "id": "123" + }, + { + "type": "dogs", + "id": "456" + } + ] + } + } + } +} +""".data(using: .utf8)! + +decoder.keyDecodingStrategy = .convertFromSnakeCase + +let personDocument = try! decoder.decode(SingleDocument.self, from: mockSinglePersonResponse) +``` + +Our `Person` object has both attributes and relationships. Generally what we care +about when accessing relationships is actually the Id(s) of the resource(s); the +loop below shows off how to access those Ids. + +```swift +let person = personDocument.body.primaryResource!.value + +let relatedDogIds = person ~> \.pets + +print("related dog Ids: \(relatedDogIds)") +``` + +To wrap things up, let's throw our dog resources into a local cache and tie +things together a bit. There are many ways to go about storing or caching +resources clientside. For additional examples of more robust solutions, take a +look at [JSONAPI-ResourceStorage](https://github.com/mattpolzin/JSONAPI-ResourceStorage). + +```swift +let dogCache = Dictionary(uniqueKeysWithValues: zip(dogs.map { $0.id }, dogs)) + +func cachedDog(_ id: Dog.Id) -> Dog? { return dogCache[id] } + +print("Our person's name is \(person.firstName) \(person.lastName).") +print("They have \((person ~> \.pets).count) pets named \((person ~> \.pets).compactMap(cachedDog).map { $0.name }.joined(separator: " and ")).") +``` + diff --git a/documentation/client-server-example.md b/documentation/examples/client-server-example.md similarity index 100% rename from documentation/client-server-example.md rename to documentation/examples/client-server-example.md diff --git a/documentation/examples/compound-example.md b/documentation/examples/compound-example.md new file mode 100644 index 0000000..18988dd --- /dev/null +++ b/documentation/examples/compound-example.md @@ -0,0 +1,134 @@ +# JSONAPI Compound Example + +We are about to walk through an example to show how easy it is to parse JSON:API +includes. Information on creating models that take advantage of more of the +features from the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +We will begin by quickly redefining the same types of `ResourceObjects` from the +[Basic Example](https://github.com/mattpolzin/JSONAPI/blob/main/documentation/basic-example.md). + +```swift +typealias Resource = JSONAPI.ResourceObject + +struct PersonDescription: ResourceObjectDescription { + + static let jsonType: String = "people" + + struct Attributes: JSONAPI.Attributes { + let firstName: Attribute + let lastName: Attribute + + let age: Attribute + } + + struct Relationships: JSONAPI.Relationships { + let pets: ToManyRelationship + } +} + +typealias Person = Resource + +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + typealias Relationships = NoRelationships +} + +typealias Dog = Resource +``` + +Next we will create similar `typealiases` for single and batch documents as we did +in the **Basic Example**, but we will allow for an include type to be specified. + +```swift +/// Our JSON:API Documents will still have no metadata or links associated with them but they will allow us to specify an include type later. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, Include, NoAPIDescription, UnknownJSONAPIError> + +typealias BatchDocument = JSONAPI.Document, NoMetadata, NoLinks, Include, NoAPIDescription, UnknownJSONAPIError> +``` + +Now let's define a mock response containing a single person and including any +dogs that are related to that person. + +```swift +// snag Foundation for Data and JSONDecoder +import Foundation + +let mockSinglePersonResponse = +""" +{ + "data": { + "type": "people", + "id": "88223", + "attributes": { + "first_name": "Lisa", + "last_name": "Offenbrook", + "age": null + }, + "relationships": { + "pets": { + "data": [ + { + "type": "dogs", + "id": "123" + }, + { + "type": "dogs", + "id": "456" + } + ] + } + } + }, + "included": [ + { + "type": "dogs", + "id": "123", + "attributes": { + "name": "Sparky" + } + }, + { + "type": "dogs", + "id": "456", + "attributes": { + "name": "Charlie Dog" + } + } + ] +} +""".data(using: .utf8)! +``` + +Parsing the above response looks almost identical to in the **Basic Example**. The +key thing to note is that instead of specifying `NoIncludes` we specify +`Include1` below. This does not mean "include one dog," it means "include one +type of thing, with that type being `Dog`." The `JSONAPI` framework comes with +built-in support for `Include2<...>`, `Include3<...>` and many more. If you wanted to include +both `Person` and `Dog` resources (perhaps because your primary `Person` resource had +a "friends" relationship), you would use `Include2`. + +```swift +let decoder = JSONDecoder() +decoder.keyDecodingStrategy = .convertFromSnakeCase + +let includeDocument = try! decoder.decode(SingleDocument>.self, from: mockSinglePersonResponse) +``` + +The `Person` is pulled out as before with `Document.body.primaryResource`. The dogs +can be accessed from `Document.body.includes`; note that because multiple types of +things can be included, we must specify that we want things of type `Dog` by using +the `JSONAPI.Includes` subscript operator. + +```swift +let person = includeDocument.body.primaryResource!.value +let dogs = includeDocument.body.includes![Dog.self] + +print("Parsed person named \(person.firstName) \(person.lastName)") +print("Parsed dogs named \(dogs.map { $0.name }.joined(separator: " and "))") +``` + diff --git a/documentation/examples/custom-errors-example.md b/documentation/examples/custom-errors-example.md new file mode 100644 index 0000000..c575ed3 --- /dev/null +++ b/documentation/examples/custom-errors-example.md @@ -0,0 +1,153 @@ + +# JSONAPI Custom Errors Example + +We are about to walk through an example of parsing a JSON:API errors response. +Information on creating models that take advantage of more of the features from +the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +First we will define a structure that can parse each of the errors we might +expect to get back from the server. This is the one type for which the framework +does not offer a generic option but we can pretty easily pick the relevant +properties from the **Error Object** description given by JSON:API +[here](https://www.google.com/url?q=https%3A%2F%2Fjsonapi.org%2Fformat%2F%23error-objects). +We will choose only to distinguish between server and client errors for this +example but that is the tip of the iceberg if you wish to make more robust error +handling for yourself. + +```swift +enum OurExampleError: JSONAPIError { + case unknownError + case server(code: Int, description: String) + case client(code: Int, description: String) + + static var unknown: OurExampleError { return .unknownError } + + // Example decoder just switches on the status code + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + let code = try Int(container.decode(String.self, forKey: .status)) + + guard let statusCode = code else { + throw DecodingError.typeMismatch(Int.self, + .init(codingPath: decoder.codingPath, + debugDescription: "Expected an integer HTTP status code.")) + } + + switch statusCode { + case 400..<500: + self = try .client(code: statusCode, description: container.decode(String.self, forKey: .detail)) + case 500..<600: + self = try .server(code: statusCode, description: container.decode(String.self, forKey: .detail)) + default: + self = .unknown + } + } + + // naturally, opposite of decoding except for needing to put something down + // for the unknown case. We choose 500 here; client won't need to encode errors + // and 500 is fitting for this situation on the server side. + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + let status: String + let detail: String + switch self { + case .server(let code, let description), + .client(let code, let description): + status = String(code) + detail = description + default: + status = "500" + detail = "Unknown problem occurred" + } + + try container.encode(status, forKey: .status) + try container.encode(detail, forKey: .detail) + } + + private enum CodingKeys: String, CodingKey { + case status + case detail + } +} +``` + +Next we will define some utility `typealiases` like we did in the +[Basic Example](https://github.com/mattpolzin/JSONAPI/blob/main/documentation/basic-example.md). +This time, we will specify that our `Document` type expects to parse +`OurExampleError`. + +```swift +typealias Resource = JSONAPI.ResourceObject + +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, OurExampleError> +``` + +We will reuse the `Dog` type from the **Basic Example**. We won't actually be +parsing this type because we are showing off error parsing. + +```swift +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + typealias Relationships = NoRelationships +} + +typealias Dog = Resource +``` + +Now let's mock up an error response. + +```swift +// snag Foundation for Data and JSONDecoder +import Foundation + +let mockErrorResponse = +""" +{ + "errors": [ + { + "status": "400", + "detail": "You made a bad request" + }, + { + "status": "500", + "detail": "The server fell over because it tried to handle your bad request" + } + ] +} +""".data(using: .utf8)! +``` + +Now we can parse the response data and switch on the response body to see if we +are dealing with an error or successful request (although we know in this case +it will be an error, of course). + +```swift +let decoder = JSONDecoder() + +let dogDocument = try! decoder.decode(SingleDocument.self, from: mockErrorResponse) + +switch dogDocument.body { +case .data(let response): + print("this would be unexpected given our mock data!") + +case .errors(let errors, meta: _, links: _): + print("The server returned the following errors:") + print(errors.map { error -> String in + switch error { + case .client(let code, let description), + .server(let code, let description): + return "\(code): \(description)" + default: + return "unknown" + } + }) +} +``` + diff --git a/documentation/examples/metadata-example.md b/documentation/examples/metadata-example.md new file mode 100644 index 0000000..d1b7ca6 --- /dev/null +++ b/documentation/examples/metadata-example.md @@ -0,0 +1,129 @@ + +# JSONAPI Metadata Example + +We are about to walk through an example of parsing JSON:API metadata. +Information on creating models that take advantage of more of the features from +the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +We will begin by quickly redefining the same types of `ResourceObjects` from the +[Basic Example](https://github.com/mattpolzin/JSONAPI/blob/main/documentation/basic-example.md). + +```swift +typealias Resource = JSONAPI.ResourceObject + +struct PersonDescription: ResourceObjectDescription { + + static let jsonType: String = "people" + + struct Attributes: JSONAPI.Attributes { + let firstName: Attribute + let lastName: Attribute + + let age: Attribute + } + + struct Relationships: JSONAPI.Relationships { + let pets: ToManyRelationship + } +} + +typealias Person = Resource + +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + typealias Relationships = NoRelationships +} + +typealias Dog = Resource +``` + +We will additionally define a structure that can parse some pagination metadata. + +```swift +struct PaginationMetadata: JSONAPI.Meta { + + let page: Page + + /// The total count of all resources of the primary type of a given response. + let total: Int + + struct Page: Codable, Equatable { + let index: Int + let size: Int + } +} +``` + +Next we will create similar `typealiases` for single and batch documents as we did +in the **Basic Example**, but we will specify that we expect the `BatchDocument` to +include our `PaginationMetadata`. + +```swift +/// Our JSON:API Documents will still have no metadata or links associated with them but they will allow us to specify an include type later. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> + +typealias BatchDocument = JSONAPI.Document, PaginationMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> +``` + +Now let's define a mock response containing a batch of dogs and pagination +metadata. + +```swift +// snag Foundation for Data and JSONDecoder +import Foundation + +let mockBatchDogResponse = +""" +{ + "data": [ + { + "type": "dogs", + "id": "123", + "attributes": { + "name": "Sparky" + } + }, + { + "type": "dogs", + "id": "456", + "attributes": { + "name": "Charlie Dog" + } + } + ], + "meta": { + "total": 10, + "page": { + "index": 2, + "size": 2 + } + } +} +""".data(using: .utf8)! +``` + +Parsing the above response looks identical to in the **Basic Example**. + +```swift +let decoder = JSONDecoder() +decoder.keyDecodingStrategy = .convertFromSnakeCase + +let metadataDocument = try! decoder.decode(BatchDocument.self, from: mockBatchDogResponse) +``` + +The `Dogs` are pulled out as before with `Document.body.primaryResource`. The +metadata is accessed by the `Document.body.metadata` property. + +```swift +let dogs = metadataDocument.body.primaryResource!.values +let metadata = metadataDocument.body.meta! + +print("Parsed dogs named \(dogs.map { $0.name }.joined(separator: " and "))") +print("Page \(metadata.page.index) out of \(metadata.total / metadata.page.size) at \(metadata.page.size) resources per page.") +``` + diff --git a/documentation/examples/patch-example.md b/documentation/examples/patch-example.md new file mode 100644 index 0000000..d7a8629 --- /dev/null +++ b/documentation/examples/patch-example.md @@ -0,0 +1,157 @@ + +# JSONAPI PATCH Example + +We are about to walk through an example to show how to take an existing resource +object and create a copy with different attributes. Additional information on +the features used here can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +The `JSONAPI` framework relies heavily on generic types so the first step will be +to alias away some of the JSON:API features we do not need for our simple +example. + +```swift +/// Our Resource objects will not have any metadata or links and they will be identified by Strings. +typealias Resource = JSONAPI.ResourceObject + +/// Our JSON:API Documents will similarly have no metadata or links associated with them. Additionally, there will be no included resources. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> +``` + +The next step is to create `ResourceObjectDescriptions` and `ResourceObjects`. For +our simple example, let's create a `Dog`. We will choose to make the properties of +our `Attributes` struct `vars` to facilitate updating them via the `ResourceObject` +`tapping` functions; an alternative approach with an immutable structure is found +later in this tutorial. + +```swift +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + var name: Attribute + } + + typealias Relationships = NoRelationships +} + +typealias Dog = Resource +``` + +At this point we have two objects that can decode JSON:API responses. To +illustrate we can mock up a dog response we might receive from the server and +parse it. + +```swift +// snag Foundation for JSONDecoder +import Foundation + +let mockDogResponse = +""" +{ + "data": { + "type": "dogs", + "id": "123", + "attributes": { + "name": "Sparky" + } + } +} +""".data(using: .utf8)! + +let decoder = JSONDecoder() + +let dogDocument = try! decoder.decode(SingleDocument.self, from: mockDogResponse) + +let dog = dogDocument.body.primaryResource!.value +``` + +We'll demonstrate renaming the dog using `ResourceObject`'s `tappingAttributes()` +function. + +```swift +let updatedDog = dog + .tappingAttributes { $0.name = .init(value: "Charlie") } +``` + +Now we can prepare a document to be used as the request body of a `PATCH` request. + +```swift +let patchRequestDocument = SingleDocument(apiDescription: .none, + body: .init(resourceObject: updatedDog), + includes: .none, + meta: .none, + links: .none) + +let requestBody = JSONEncoder().encode(patchRequestDocument) +``` + +Instead of actually sending off a `PATCH` request, we will just print the request +body out to prove to ourselves that the name was updated. + +```swift +print(String(data: requestBody, encoding: .utf8)!) +``` + +---- + +Alternatively, the `Attributes` struct could have been defined with `let` +properties. Not much changes, but the `name` cannot be mutated so the entire +struct must be recreated. We will take this opportunity to use the +`ResourceObject` `replacingAttributes()` method to contrast it to the +`tappingAttributes()` method. + +The `ImmutableDogDescription` below is almost identical to `DogDescription`, but the `name` +is a `let` constant. + +```swift +struct ImmutableDogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + typealias Relationships = NoRelationships +} + +typealias Dog2 = Resource +``` + +We can use the same mock data for a single dog document and parse it as a `Dog2`. + +```swift +let dogDocument2 = try! decoder.decode(SingleDocument.self, from: mockDogResponse) + +let dog2 = dogDocument2.body.primaryResource!.value +``` + +We could still use `tappingAttributes()` but we cannot mutate the name property of +the new `Attributes` struct, so we will use `replacingAttributes()` instead. This +method takes as its parameter a function that returns the new attributes. + +```swift +let updatedDog2 = dog2 + .replacingAttributes { _ in + return .init(name: .init(value: "Toby")) +} +``` + +Now create a request document. + +```swift +let patchRequestDocument2 = SingleDocument(apiDescription: .none, + body: .init(resourceObject: updatedDog2), + includes: .none, + meta: .none, + links: .none) + +let requestBody2 = JSONEncoder().encode(patchRequestDocument2) +``` + +Once again, we'll print the request body out instead of sending it with a `PATCH` +request. + +```swift +print(String(data: requestBody2, encoding: .utf8)!) +``` + diff --git a/documentation/examples/resource-storage-example.md b/documentation/examples/resource-storage-example.md new file mode 100644 index 0000000..4e63ae7 --- /dev/null +++ b/documentation/examples/resource-storage-example.md @@ -0,0 +1,204 @@ + +# JSONAPI Resource Storage Example + +We are about to walk through an example to show one possible way to handle +resource caching on the clientside. This example depends on both +[JSONAPI](https://github.com/mattpolzin/JSONAPI) and +[JSONAPI-ResourceStorage](https://github.com/mattpolzin/JSONAPI-ResourceStorage). + +Information on creating models that take advantage of more of the features from +the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +We will begin by quickly redefining the same types of `ResourceObjects` from the +[Basic Example](https://github.com/mattpolzin/JSONAPI/blob/main/documentation/basic-example.md). + +```swift +typealias Resource = JSONAPI.ResourceObject + +struct PersonDescription: ResourceObjectDescription { + + static let jsonType: String = "people" + + struct Attributes: JSONAPI.Attributes { + let firstName: Attribute + let lastName: Attribute + + /// User is not required to specify their age. + let age: Attribute + } + + struct Relationships: JSONAPI.Relationships { + let pets: ToManyRelationship + } +} + +typealias Person = Resource + +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + typealias Relationships = NoRelationships +} + +typealias Dog = Resource +``` + +We can borrow the `Document` `typealiases` from the +[Compound Example](https://github.com/mattpolzin/JSONAPI/blob/main/documentation/compound-example.md). + +```swift +/// Our JSON:API Documents will still have no metadata or links associated with them but they will allow us to specify an include type later. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, Include, NoAPIDescription, UnknownJSONAPIError> + +typealias BatchDocument = JSONAPI.Document, NoMetadata, NoLinks, Include, NoAPIDescription, UnknownJSONAPIError> +``` + +We define a resource cache capable of storing `Person` and `Dog` types. As a +convenience, we define what it means to merge two `Caches`. The `merge` method is +not a requirement of `ResourceCache` but it will allow us to easily add resources +from our JSON:API document to our cache. + +We are going to use a value type for the cache. A reference type (like the one +in the `JSONAPIResourceStore` module in this package) could also be used, but an +equatable value type works well when you want your app state to be comparable so +your logic can determine when the cache has changed. + +```swift +struct Cache: Equatable, ResourceCache { + var people: ResourceHash = [:] + var dogs: ResourceHash = [:] + + mutating func merge(_ other: Cache) { + // we merge and resolve conflicts with `other`'s versions so we effectively + // "add or update" each resource. + people.merge(other.people, uniquingKeysWith: { $1 }) + dogs.merge(other.dogs, uniquingKeysWith: { $1 }) + } +} +``` + +We need to tell people and dogs where to find themselves in the cache. + +```swift +extension PersonDescription: Materializable { + public static var cachePath: WritableKeyPath> { \.people } +} + +extension DogDescription: Materializable { + public static var cachePath: WritableKeyPath> { \.dogs } +} +``` + +Let's create our app-wide cache of resources. We are going to use a value type; +a reference type could be used just as well, but a value type that is equatable. + +```swift +var cache = Cache() +``` + +Now let's define a mock response containing a single person and including any +dogs that are related to that person. + +```swift +let mockSinglePersonResponse = +""" +{ + "data": { + "type": "people", + "id": "88223", + "attributes": { + "first_name": "Lisa", + "last_name": "Offenbrook", + "age": null + }, + "relationships": { + "pets": { + "data": [ + { + "type": "dogs", + "id": "123" + }, + { + "type": "dogs", + "id": "456" + } + ] + } + } + }, + "included": [ + { + "type": "dogs", + "id": "123", + "attributes": { + "name": "Sparky" + } + }, + { + "type": "dogs", + "id": "456", + "attributes": { + "name": "Charlie Dog" + } + } + ] +} +""".data(using: .utf8)! +``` + +We decode a document like the one mocked above as a `SingleDocument` specialized +on a primary resource type of `Person` and an include type of `Include1` +(a.k.a. all included resources will be of the same type: `Dog`). + +```swift +let decoder = JSONDecoder() +decoder.keyDecodingStrategy = .convertFromSnakeCase + +let document = try decoder.decode(SingleDocument>.self, from: mockSinglePersonResponse) +``` + +We can ask `document` for a cache of resources it contains. Then we can merge that +into our app-wide cache. + +```swift +if let documentResources = document.resourceCache() { + cache.merge(documentResources) +} else { + // probably time to check for an error response. +} +``` + +We can access all people in the cache. + +```swift +for person in cache.people.values { + print("\(person.firstName) \(person.lastName) has \((person ~> \.pets).count) dogs.") +} +``` + +We can access those dogs via the cache using the cache's subscript operator. + +```swift +for person in cache.people.values { + print("\(person.firstName) \(person.lastName) has pets named:") + for dogId in (person ~> \.pets) { + print(cache[dogId]?.name ?? "missing dog info") + } +} +``` + +We can also map the dog ids to materialized dogs. + +```swift +for person in cache.people.values { + let dogs = (person ~> \.pets).compactMap { $0.materialized(from: cache) } + let dogNames = dogs.map(\.name).joined(separator: ", ") + + print("\(person.firstName) \(person.lastName) has pets named: \(dogNames)") +} +``` + diff --git a/documentation/examples/serverside-get-example.md b/documentation/examples/serverside-get-example.md new file mode 100644 index 0000000..a3dc390 --- /dev/null +++ b/documentation/examples/serverside-get-example.md @@ -0,0 +1,179 @@ + +# JSONAPI Serverside GET Example + +We are about to walk through a basic example of serializing a simple model. +Information on creating models that take advantage of more of the features from +the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +Note that the first two steps here are almost identical to the first two steps +in the +[Clientside Basic Example](https://github.com/mattpolzin/JSONAPI/blob/main/documentation/basic-example.md). +The same Swift resource types you create with this framework can be used by the +client and the server. + +The `JSONAPI` framework relies heavily on generic types so the first step will be +to alias away some of the JSON:API features we do not need for our simple +example. + +```swift +/// Our Resource objects will not have any metadata or links and they will be identified by Strings. +typealias Resource = JSONAPI.ResourceObject + +/// Our JSON:API Documents will similarly have no metadata or links associated with them. Additionally, there will be no included resources. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> + +typealias BatchDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> +``` + +The next step is to create `ResourceObjectDescriptions` and `ResourceObjects`. For +our simple example, let's create a `Person` and a `Dog`. + +```swift +enum API {} + +struct PersonDescription: ResourceObjectDescription { + // by common convention, we will use the plural form + // of the noun as the JSON:API "type" + static let jsonType: String = "people" + + struct Attributes: JSONAPI.Attributes { + let firstName: Attribute + let lastName: Attribute + + // we mark this attribute as "nullable" because the user can choose + // not to specify an age if they would like to. + let age: Attribute + } + + struct Relationships: JSONAPI.Relationships { + // we will define "Dog" next + let pets: ToManyRelationship + } +} + +// this typealias is optional, but it makes working with resource objects much +// more user friendly. +extension API { + typealias Person = Resource +} + +struct DogDescription: ResourceObjectDescription { + static let jsonType: String = "dogs" + + struct Attributes: JSONAPI.Attributes { + let name: Attribute + } + + // we could relate dogs back to their owners, but for the sake of this example + // we will instead show how you would create a resource with no relationships. + typealias Relationships = NoRelationships +} + +extension API { + typealias Dog = Resource +} +``` + +At this point we have two objects that can encode JSON:API responses. To +illustrate we will skip over the details of reading from the database and assume +we have some data ready to be turned into a JSON:API response for a collection +of `Dogs`. + +```swift +// snag Foundation for JSONDecoder +import Foundation + +// This is just a standin for whatever models you've got coming out of the database. +enum DB { + struct Dog { + let id: Int + let name: String + } +} + +// you could handle this any number of ways, but here we will write an extension +// that gets you the `JSONAPI` models from the database models. +extension DB.Dog { + var serializable: API.Dog { + let attributes = API.Dog.Attributes(name: .init(value: name)) + return API.Dog(id: .init(rawValue: String(id)), + attributes: attributes, + relationships: .none, + meta: .none, + links: .none) + } +} + +let dogs = [ + DB.Dog(id: 123, name: "Sparky"), + DB.Dog(id: 456, name: "Charlie Dog") +].map { $0.serializable } + + +let encoder = JSONEncoder() +encoder.outputFormatting = .prettyPrinted + +let primaryResources = ManyResourceBody(resourceObjects: dogs) + +let dogsDocument = BatchDocument(apiDescription: .none, + body: primaryResources, + includes: .none, + meta: .none, + links: .none) + +let dogsResponse = try! encoder.encode(dogsDocument) + +// At this point you can send the response data to the client in whatever way you like. + +print("dogs response: \(String(data: dogsResponse, encoding: .utf8)!)") +``` + +Let's look at a single `Person` response as well. + +```swift +extension DB { + struct Person { + let id: Int + let firstName: String + let lastName: String + let age: Int? + + /// relationship to dogs created as array of String Ids + let dogs: [Int] + } +} + +extension DB.Person { + var serializable: API.Person { + let attributes = API.Person.Attributes(firstName: .init(value: firstName), + lastName: .init(value: lastName), + age: .init(value: age)) + let relationships = API.Person.Relationships(pets: .init(ids: dogs.map { API.Dog.Id(rawValue: String($0)) })) + + return API.Person(id: .init(rawValue: String(id)), + attributes: attributes, + relationships: relationships, + meta: .none, + links: .none) + } +} + +let person = DB.Person(id: 9876, + firstName: "Julie", + lastName: "Stone", + age: nil, + dogs: [123, 456]).serializable + +let personDocument = SingleDocument(apiDescription: .none, + body: .init(resourceObject: person), + includes: .none, + meta: .none, + links: .none) + +let personResponse = try! encoder.encode(personDocument) + +// At this point you can send the response data to the client in whatever way you like. + +print("person response: \(String(data: personResponse, encoding: .utf8)!)") +``` + diff --git a/documentation/examples/serverside-post-example.md b/documentation/examples/serverside-post-example.md new file mode 100644 index 0000000..5be338f --- /dev/null +++ b/documentation/examples/serverside-post-example.md @@ -0,0 +1,152 @@ + +# JSONAPI Serverside POST Example + +We are about to walk through an example handling a POST (resource creation) +request. Information on creating models that take advantage of more of the +features from the JSON:API Specification can be found in the [README](https://github.com/mattpolzin/JSONAPI/blob/main/README.md). + +We will identify our resources using `UUID`s. + +```swift +// If we wanted to, we could just make `UUID` a `RawIdType` +// extension UUID: RawIdType {} + +// We will go a step further and make it a `CreatableRawIdType` and let `JSONAPI` +// create new unique Ids for people in the POST handling code farther down in this +// example. +extension UUID: CreatableRawIdType { + public static func unique() -> UUID { + return UUID() + } +} +``` + +The `JSONAPI` framework relies heavily on generic types so the first step will be +to alias away some of the JSON:API features we do not need for our simple +example. + +```swift +/// Our Resource objects will not have any metadata or links and they will be identified by UUIDs. +typealias Resource = JSONAPI.ResourceObject + +/// The client will send us a POST request with an unidenfitied resource object. We will call this a "new resource object" +typealias New = JSONAPI.ResourceObject + +/// Our JSON:API Documents will similarly have no metadata or links associated with them. Additionally, there will be no included resources. +typealias SingleDocument = JSONAPI.Document, NoMetadata, NoLinks, NoIncludes, NoAPIDescription, UnknownJSONAPIError> +``` + +The next step is to create `ResourceObjectDescriptions` and `ResourceObjects`. For +our simple example, we will handle a `POST` request for a `Person` resource. + +```swift +enum API {} + +struct PersonDescription: ResourceObjectDescription { + // by common convention, we will use the plural form + // of the noun as the JSON:API "type" + static let jsonType: String = "people" + + struct Attributes: JSONAPI.Attributes { + let firstName: Attribute + let lastName: Attribute + + // we mark this attribute as "nullable" because the user can choose + // not to specify an age if they would like to. + let age: Attribute + } + + typealias Relationships = NoRelationships +} + +// this typealias is optional, but it makes working with resource objects much +// more user friendly. +extension API { + typealias Person = Resource +} +``` + +To illustrate using the `JSONAPI` framework, we will skip over the details of +database reading/writing. Let's mock up a database model for a `Person`. + +```swift +// snag Foundation for JSONDecoder +import Foundation + +// This is just a standin for whatever models you've got coming out of the database. +enum DB { + struct Person { + let id: String + let firstName: String + let lastName: String + let age: Int? + } +} + +// you could handle this any number of ways, but here we will write an initializer +// that gets you a database model from the `JSONAPI` model. +extension DB.Person { + + init(_ person: API.Person) { + id = "\(person.id.rawValue)" + firstName = person.firstName + lastName = person.lastName + age = person.age + } +} +``` + +Now we'll handle a `POST` request by creating a new database record (we'll skip +this detail) and responding with a `Person` resource. + +```swift +// NOTE this request has no Id because the client is requesting this new `Person` be created. +let mockPersonRequest = +""" +{ + "data": { + "type": "people", + "attributes": { + "first_name": "Jimmie", + "last_name": "Glows", + "age": 53 + } + } +} +""".data(using: .utf8)! + +let decoder = JSONDecoder() +decoder.keyDecodingStrategy = .convertFromSnakeCase + +// We will decode a "new" resource (see typealiases earlier in this example) +let requestedPersonDocument = try! decoder.decode(SingleDocument>.self, from: mockPersonRequest) +let requestedPerson = requestedPersonDocument.body.primaryResource!.value + +// Our DB.Person initializer expects an identified `Person`, not a `New` +// but we can let the `JSONAPI` framework create a new `UUID` for us: +let identifiedPerson = requestedPerson.identified(byType: UUID.self) + +let dbPerson = DB.Person(identifiedPerson) + +// Here's where we would save our `dbPerson` to te database, if we had an +// actualy database connection in this example. We'd also create our response from +// the result of that database save, ideally. We are going to skip those details +// and pretend the database write was successful. + +// finally, let's create a response +let encoder = JSONEncoder() +encoder.keyEncodingStrategy = .convertToSnakeCase +encoder.outputFormatting = .prettyPrinted + +let responseData = try! encoder.encode(SingleDocument(apiDescription: .none, + body: .init(resourceObject: identifiedPerson), + includes: .none, + meta: .none, + links: .none)) + +// Send it off to the client! + +print("response body:") +print("\(String(data: responseData, encoding: .utf8)!)") +``` + From 28a8a30334b07c7a813063a4496f6d2c25e4fb76 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 28 Apr 2025 09:40:32 -0500 Subject: [PATCH 28/33] update swift version shield and build/tests shield --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3fe2993..67946cd 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # JSONAPI -[![MIT license](http://img.shields.io/badge/license-MIT-lightgrey.svg)](http://opensource.org/licenses/MIT) [![Swift 5.2+](http://img.shields.io/badge/Swift-5.2/5.3/5.4-blue.svg)](https://swift.org) [![Build Status](https://app.bitrise.io/app/c8295b9589aa401e/status.svg?token=vzcyqWD5bQ4xqQfZsaVzNw&branch=main)](https://app.bitrise.io/app/c8295b9589aa401e) +[![MIT license](http://img.shields.io/badge/license-MIT-lightgrey.svg)](http://opensource.org/licenses/MIT) [![Swift 5.2+](http://img.shields.io/badge/Swift-5.2+-blue.svg)](https://swift.org) [![Tests](https://github.com/mattpolzin/JSONAPI/actions/workflows/tests.yml/badge.svg)](https://github.com/mattpolzin/JSONAPI/actions/workflows/tests.yml) A Swift package for encoding to- and decoding from **JSON API** compliant requests and responses. From 8c15b7838933c565f71ad4ddb04735b662077178 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Thu, 11 Sep 2025 09:24:23 -0500 Subject: [PATCH 29/33] remove support for non-SwiftPM package managers. require Swift 6.0+. --- .github/workflows/tests.yml | 19 +---- JSONAPI.podspec | 141 ------------------------------------ Package.resolved | 25 +++---- Package.swift | 10 +-- README.md | 28 +------ 5 files changed, 25 insertions(+), 198 deletions(-) delete mode 100644 JSONAPI.podspec diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9644cf8..df8f649 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,23 +13,12 @@ jobs: fail-fast: false matrix: image: - - swift:5.2-focal - - swift:5.2-centos8 - - swift:5.3-focal - - swift:5.3-centos8 - - swift:5.4-focal - - swift:5.4-centos8 - - swift:5.5-focal - - swift:5.5-centos8 - - swift:5.6-focal -# - swift:5.7-focal -# - swift:5.8-focal -# - swift:5.9-focal -# - swift:5.10-focal + - swift:6.0 + - swift:6.1 container: ${{ matrix.image }} steps: - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: Run tests run: swift test --enable-test-discovery osx: @@ -39,6 +28,6 @@ jobs: uses: maxim-lobanov/setup-xcode@v1 with: { 'xcode-version': 'latest' } - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v5 - name: Run tests run: swift test --enable-test-discovery diff --git a/JSONAPI.podspec b/JSONAPI.podspec deleted file mode 100644 index 4a22764..0000000 --- a/JSONAPI.podspec +++ /dev/null @@ -1,141 +0,0 @@ -# -# Be sure to run `pod spec lint JSONAPI.podspec' to ensure this is a -# valid spec and to remove all comments including this before submitting the spec. -# -# To learn more about Podspec attributes see https://docs.cocoapods.org/specification.html -# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ -# - -Pod::Spec.new do |spec| - - # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # These will help people to find your library, and whilst it - # can feel like a chore to fill in it's definitely to your advantage. The - # summary should be tweet-length, and the description more in depth. - # - - spec.name = "MP-JSONAPI" - spec.version = "5.1.0" - spec.summary = "Swift Codable JSON API framework." - - # This description is used to generate tags and improve search results. - # * Think: What does it do? Why did you write it? What is the focus? - # * Try to keep it short, snappy and to the point. - # * Write the description between the DESC delimiters below. - # * Finally, don't worry about the indent, CocoaPods strips it! - spec.description = <<-DESC - A Swift package for encoding to- and decoding from JSON API compliant requests and responses. - -See the JSON API Spec here: https://jsonapi.org/format/ - DESC - - spec.homepage = "https://github.com/mattpolzin/JSONAPI" - # spec.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" - - - # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Licensing your code is important. See https://choosealicense.com for more info. - # CocoaPods will detect a license file if there is a named LICENSE* - # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. - # - - # spec.license = "MIT" - spec.license = { :type => "MIT", :file => "LICENSE.txt" } - - - # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Specify the authors of the library, with email addresses. Email addresses - # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also - # accepts just a name if you'd rather not provide an email address. - # - # Specify a social_media_url where others can refer to, for example a twitter - # profile URL. - # - - spec.author = { "Mathew Polzin" => "matt.polzin@gmail.com" } - # Or just: spec.author = "Mathew Polzin" - # spec.authors = { "Mathew Polzin" => "matt.polzin@gmail.com" } - # spec.social_media_url = "https://twitter.com/Mathew Polzin" - - # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # If this Pod runs only on iOS or OS X, then specify the platform and - # the deployment target. You can optionally include the target after the platform. - # - - # spec.platform = :ios - # spec.platform = :ios, "5.0" - - # When using multiple platforms - spec.ios.deployment_target = "8.0" - spec.osx.deployment_target = "10.9" - # spec.watchos.deployment_target = "2.0" - # spec.tvos.deployment_target = "9.0" - - - # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Specify the location from where the source should be retrieved. - # Supports git, hg, bzr, svn and HTTP. - # - - spec.source = { :git => "https://github.com/mattpolzin/JSONAPI.git", :tag => "#{spec.version}" } - - - # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # CocoaPods is smart about how it includes source code. For source files - # giving a folder will include any swift, h, m, mm, c & cpp files. - # For header files it will include any header in the folder. - # Not including the public_header_files will make all headers public. - # - - spec.source_files = "Sources/JSONAPI/**/*.{swift}" - # spec.exclude_files = "Classes/Exclude" - - # spec.public_header_files = "Classes/**/*.h" - - - # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # A list of resources included with the Pod. These are copied into the - # target bundle with a build phase script. Anything else will be cleaned. - # You can preserve files from being cleaned, please don't preserve - # non-essential files like tests, examples and documentation. - # - - # spec.resource = "icon.png" - # spec.resources = "Resources/*.png" - - # spec.preserve_paths = "FilesToSave", "MoreFilesToSave" - - - # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Link your library with frameworks, or libraries. Libraries do not include - # the lib prefix of their name. - # - - # spec.frameworks = "SomeFramework", "AnotherFramework" - - # spec.library = "iconv" - # spec.libraries = "iconv", "xml2" - - - # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # If your library depends on compiler flags you can set them in the xcconfig hash - # where they will only apply to your library. If you depend on other Podspecs - # you can include multiple dependencies to ensure it works. - - spec.swift_version = "5.2" - spec.module_name = "JSONAPI" - # spec.requires_arc = true - - # spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } - spec.dependency "Poly", "~> 2.6" - -end diff --git a/Package.resolved b/Package.resolved index f7c521e..f0e1825 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,16 +1,15 @@ { - "object": { - "pins": [ - { - "package": "Poly", - "repositoryURL": "https://github.com/mattpolzin/Poly.git", - "state": { - "branch": null, - "revision": "99e2e8b575620369be52fe348c0dd72028e3674c", - "version": "2.8.0" - } + "originHash" : "54aae326cbf0090b80ab7860957be502f5396744f5579cf522be7cb3ffa67caf", + "pins" : [ + { + "identity" : "poly", + "kind" : "remoteSourceControl", + "location" : "https://github.com/mattpolzin/Poly.git", + "state" : { + "revision" : "37c942daa23ab373ce05ef87f42103342e59cf3a", + "version" : "3.0.0" } - ] - }, - "version": 1 + } + ], + "version" : 3 } diff --git a/Package.swift b/Package.swift index 81b978c..642091f 100644 --- a/Package.swift +++ b/Package.swift @@ -1,12 +1,12 @@ -// swift-tools-version:5.2 +// swift-tools-version:6.0 import PackageDescription let package = Package( name: "JSONAPI", platforms: [ - .macOS(.v10_10), - .iOS(.v10) + .macOS(.v10_15), + .iOS(.v13) ], products: [ .library( @@ -17,7 +17,7 @@ let package = Package( targets: ["JSONAPITesting"]) ], dependencies: [ - .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "2.8.0")), + .package(url: "https://github.com/mattpolzin/Poly.git", .upToNextMajor(from: "3.0.0")), ], targets: [ .target( @@ -33,5 +33,5 @@ let package = Package( name: "JSONAPITestingTests", dependencies: ["JSONAPI", "JSONAPITesting"]) ], - swiftLanguageVersions: [.v5] + swiftLanguageModes: [.v5, .v6] ) diff --git a/README.md b/README.md index 67946cd..873a186 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # JSONAPI -[![MIT license](http://img.shields.io/badge/license-MIT-lightgrey.svg)](http://opensource.org/licenses/MIT) [![Swift 5.2+](http://img.shields.io/badge/Swift-5.2+-blue.svg)](https://swift.org) [![Tests](https://github.com/mattpolzin/JSONAPI/actions/workflows/tests.yml/badge.svg)](https://github.com/mattpolzin/JSONAPI/actions/workflows/tests.yml) +[![MIT license](http://img.shields.io/badge/license-MIT-lightgrey.svg)](http://opensource.org/licenses/MIT) [![Swift 6.0+](http://img.shields.io/badge/Swift-6.0+-blue.svg)](https://swift.org) [![Tests](https://github.com/mattpolzin/JSONAPI/actions/workflows/tests.yml/badge.svg)](https://github.com/mattpolzin/JSONAPI/actions/workflows/tests.yml) A Swift package for encoding to- and decoding from **JSON API** compliant requests and responses. @@ -58,35 +58,15 @@ If you find something wrong with this library and it isn't already mentioned und ## Dev Environment ### Prerequisites -1. Swift 5.2+ -2. Swift Package Manager, Xcode 11+, or Cocoapods +1. Swift 6.0+ +2. Swift Package Manager ### Swift Package Manager Just include the following in your package's dependencies and add `JSONAPI` to the dependencies for any of your targets. ```swift -.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "5.1.0") +.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "6.0.0") ``` -### Xcode project -With Xcode 11+, you can open the folder containing this repository. There is no need for an Xcode project, but you can generate one with `swift package generate-xcodeproj`. - -### CocoaPods -To use this framework in your project via Cocoapods, add the following dependencies to your Podfile. -```ruby -pod 'Poly', :git => 'https://github.com/mattpolzin/Poly.git' -pod 'MP-JSONAPI', :git => 'https://github.com/mattpolzin/JSONAPI.git' -``` - -### Carthage -This library does not support the Carthage package manager. This is intentional to avoid an additional dependency on Xcode and the Xcode's project files as their format changes throughout versions (in addition to the complexity of maintaining different shared schemes for each supported operating system). - -The difference between supporting and not supporting Carthage is the difference between maintaining an Xcode project with at least one shared build scheme; I encourage those that need Carthage support to fork this repository and add support to their fork by committing an Xcode project (you can generate one as described in the [Xcode project](#xcode-project) section above). Once an Xcode project is generated, you need to mark at least one scheme as [shared](https://github.com/Carthage/Carthage#share-your-xcode-schemes). - -### 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. - -Note that Playground support for importing non-system Frameworks is still a bit touchy as of Swift 4.2. Sometimes building, cleaning and building, or commenting out and then uncommenting import statements (especially in the` Entities.swift` Playground Source file) can get things working for me when I am getting an error about `JSONAPI` not being found. - ## Deeper Dive - [Project Status](./documentation/project-status.md) - [Server & Client Example](./documentation/examples/client-server-example.md) From 07503f207408a9604f59bf7ce759cbb72c58dc59 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sat, 13 Sep 2025 17:10:28 -0500 Subject: [PATCH 30/33] a few less controversial changes for starters --- Sources/JSONAPI/Error/BasicJSONAPIError.swift | 6 ++++-- Sources/JSONAPI/Error/GenericJSONAPIError.swift | 2 +- Sources/JSONAPI/JSONAPICodingError.swift | 2 +- Sources/JSONAPI/Resource/Id.swift | 2 +- Sources/JSONAPI/Resource/Poly+PrimaryResource.swift | 6 ++++-- .../Resource Object/ResourceObjectDecodingError.swift | 4 ++-- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/Sources/JSONAPI/Error/BasicJSONAPIError.swift b/Sources/JSONAPI/Error/BasicJSONAPIError.swift index 2c18e69..b966229 100644 --- a/Sources/JSONAPI/Error/BasicJSONAPIError.swift +++ b/Sources/JSONAPI/Error/BasicJSONAPIError.swift @@ -39,7 +39,7 @@ public struct BasicJSONAPIErrorPayload: Codable, Eq self.source = source } - public struct Source: Codable, Equatable { + public struct Source: Codable, Equatable, Sendable { /// 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 @@ -70,6 +70,8 @@ public struct BasicJSONAPIErrorPayload: Codable, Eq } } +extension BasicJSONAPIErrorPayload: Sendable where IdType: Sendable {} + /// `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 @@ -100,4 +102,4 @@ public struct BasicJSONAPIErrorPayload: Codable, Eq /// 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 = GenericJSONAPIError> +public typealias BasicJSONAPIError = GenericJSONAPIError> diff --git a/Sources/JSONAPI/Error/GenericJSONAPIError.swift b/Sources/JSONAPI/Error/GenericJSONAPIError.swift index 473caac..457e4f7 100644 --- a/Sources/JSONAPI/Error/GenericJSONAPIError.swift +++ b/Sources/JSONAPI/Error/GenericJSONAPIError.swift @@ -8,7 +8,7 @@ /// `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: JSONAPIError, CustomStringConvertible { +public enum GenericJSONAPIError: JSONAPIError, CustomStringConvertible { case unknownError case error(ErrorPayload) diff --git a/Sources/JSONAPI/JSONAPICodingError.swift b/Sources/JSONAPI/JSONAPICodingError.swift index da0705d..8cf889b 100644 --- a/Sources/JSONAPI/JSONAPICodingError.swift +++ b/Sources/JSONAPI/JSONAPICodingError.swift @@ -13,7 +13,7 @@ public enum JSONAPICodingError: Swift.Error { case missingOrMalformedMetadata(path: [CodingKey]) case missingOrMalformedLinks(path: [CodingKey]) - public enum Quantity: String, Equatable { + public enum Quantity: String, Equatable, Sendable { case one case many diff --git a/Sources/JSONAPI/Resource/Id.swift b/Sources/JSONAPI/Resource/Id.swift index 2fc4bac..fd05123 100644 --- a/Sources/JSONAPI/Resource/Id.swift +++ b/Sources/JSONAPI/Resource/Id.swift @@ -31,7 +31,7 @@ extension String: RawIdType {} /// A type that can be used as the `MaybeRawId` for a `ResourceObject` that does not /// have an Id (most likely because it was created by a client and the server will be responsible /// for assigning it an Id). -public struct Unidentified: MaybeRawId, CustomStringConvertible { +public struct Unidentified: MaybeRawId, CustomStringConvertible, Sendable { public init() {} public var description: String { return "Unidentified" } diff --git a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift index 1443610..95f04a7 100644 --- a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift +++ b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift @@ -15,12 +15,12 @@ import Poly /// disparate types under one roof for /// the purposes of JSON API compliant /// encoding or decoding. -public typealias EncodableJSONPoly = Poly & EncodablePrimaryResource +public typealias EncodableJSONPoly = Poly & EncodablePrimaryResource & Sendable public typealias EncodablePolyWrapped = Encodable & Equatable public typealias CodablePolyWrapped = EncodablePolyWrapped & Decodable -extension Poly0: CodablePrimaryResource { +extension Poly0: @retroactive Encodable, @retroactive Decodable { public init(from decoder: Decoder) throws { throw JSONAPICodingError.illegalDecoding("Attempted to decode Poly0, which should represent a thing that is not expected to be found in a document.", path: decoder.codingPath) } @@ -30,6 +30,8 @@ extension Poly0: CodablePrimaryResource { } } +extension Poly0: CodablePrimaryResource {} + // MARK: - 1 type extension Poly1: EncodablePrimaryResource, OptionalEncodablePrimaryResource where A: EncodablePolyWrapped {} diff --git a/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift b/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift index 004e03c..d458605 100644 --- a/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift +++ b/Sources/JSONAPI/Resource/Resource Object/ResourceObjectDecodingError.swift @@ -13,7 +13,7 @@ public struct ResourceObjectDecodingError: Swift.Error, Equatable { static let entireObject = "entire object" - public enum Cause: Equatable { + public enum Cause: Equatable, Sendable { case keyNotFound case valueNotFound case typeMismatch(expectedTypeName: String) @@ -26,7 +26,7 @@ public struct ResourceObjectDecodingError: Swift.Error, Equatable { } } - public enum Location: String, Equatable { + public enum Location: String, Equatable, Sendable { case attributes case relationships case relationshipType From 8f66c9247dff207b0bdee1bece897140b304e50a Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sat, 13 Sep 2025 17:17:07 -0500 Subject: [PATCH 31/33] silence some retroactive conformance warnings where they are acceptable risks --- Sources/JSONAPITesting/Attribute+Literal.swift | 6 +++--- Sources/JSONAPITesting/Optional+Literal.swift | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/JSONAPITesting/Attribute+Literal.swift b/Sources/JSONAPITesting/Attribute+Literal.swift index b631bab..f817a32 100644 --- a/Sources/JSONAPITesting/Attribute+Literal.swift +++ b/Sources/JSONAPITesting/Attribute+Literal.swift @@ -39,7 +39,7 @@ extension Attribute: ExpressibleByFloatLiteral where RawValue: ExpressibleByFloa } } -extension Optional: ExpressibleByFloatLiteral where Wrapped: ExpressibleByFloatLiteral { +extension Optional: @retroactive ExpressibleByFloatLiteral where Wrapped: ExpressibleByFloatLiteral { public typealias FloatLiteralType = Wrapped.FloatLiteralType public init(floatLiteral value: FloatLiteralType) { @@ -55,7 +55,7 @@ extension Attribute: ExpressibleByBooleanLiteral where RawValue: ExpressibleByBo } } -extension Optional: ExpressibleByBooleanLiteral where Wrapped: ExpressibleByBooleanLiteral { +extension Optional: @retroactive ExpressibleByBooleanLiteral where Wrapped: ExpressibleByBooleanLiteral { public typealias BooleanLiteralType = Wrapped.BooleanLiteralType public init(booleanLiteral value: BooleanLiteralType) { @@ -71,7 +71,7 @@ extension Attribute: ExpressibleByIntegerLiteral where RawValue: ExpressibleByIn } } -extension Optional: ExpressibleByIntegerLiteral where Wrapped: ExpressibleByIntegerLiteral { +extension Optional: @retroactive ExpressibleByIntegerLiteral where Wrapped: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = Wrapped.IntegerLiteralType public init(integerLiteral value: IntegerLiteralType) { diff --git a/Sources/JSONAPITesting/Optional+Literal.swift b/Sources/JSONAPITesting/Optional+Literal.swift index 8c87fab..f0e03d6 100644 --- a/Sources/JSONAPITesting/Optional+Literal.swift +++ b/Sources/JSONAPITesting/Optional+Literal.swift @@ -5,7 +5,7 @@ // Created by Mathew Polzin on 11/29/18. // -extension Optional: ExpressibleByUnicodeScalarLiteral where Wrapped: ExpressibleByUnicodeScalarLiteral { +extension Optional: @retroactive ExpressibleByUnicodeScalarLiteral where Wrapped: ExpressibleByUnicodeScalarLiteral { public typealias UnicodeScalarLiteralType = Wrapped.UnicodeScalarLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { @@ -13,7 +13,7 @@ extension Optional: ExpressibleByUnicodeScalarLiteral where Wrapped: Expressible } } -extension Optional: ExpressibleByExtendedGraphemeClusterLiteral where Wrapped: ExpressibleByExtendedGraphemeClusterLiteral { +extension Optional: @retroactive ExpressibleByExtendedGraphemeClusterLiteral where Wrapped: ExpressibleByExtendedGraphemeClusterLiteral { public typealias ExtendedGraphemeClusterLiteralType = Wrapped.ExtendedGraphemeClusterLiteralType public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { @@ -21,7 +21,7 @@ extension Optional: ExpressibleByExtendedGraphemeClusterLiteral where Wrapped: E } } -extension Optional: ExpressibleByStringLiteral where Wrapped: ExpressibleByStringLiteral { +extension Optional: @retroactive ExpressibleByStringLiteral where Wrapped: ExpressibleByStringLiteral { public typealias StringLiteralType = Wrapped.StringLiteralType public init(stringLiteral value: StringLiteralType) { From f2e3317242eb53c822f284995f4f8d8b0f03fbe2 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sat, 13 Sep 2025 17:41:03 -0500 Subject: [PATCH 32/33] and now to conditionally apply sendable more broadly --- Sources/JSONAPI/Document/APIDescription.swift | 4 ++++ Sources/JSONAPI/Document/Document.swift | 15 +++++++++++++++ Sources/JSONAPI/Document/Includes.swift | 2 ++ Sources/JSONAPI/Document/ResourceBody.swift | 6 ++++++ Sources/JSONAPI/Meta/Links.swift | 4 +++- Sources/JSONAPI/Meta/Meta.swift | 2 +- Sources/JSONAPI/Resource/Attribute.swift | 4 ++++ Sources/JSONAPI/Resource/Id.swift | 2 ++ .../JSONAPI/Resource/Poly+PrimaryResource.swift | 2 +- Sources/JSONAPI/Resource/Relationship.swift | 15 +++++++++++++++ .../Resource/Resource Object/ResourceObject.swift | 11 +++++++++-- .../Comparisons/IncludesCompareTests.swift | 4 ++-- 12 files changed, 64 insertions(+), 7 deletions(-) diff --git a/Sources/JSONAPI/Document/APIDescription.swift b/Sources/JSONAPI/Document/APIDescription.swift index cb417a6..123d056 100644 --- a/Sources/JSONAPI/Document/APIDescription.swift +++ b/Sources/JSONAPI/Document/APIDescription.swift @@ -21,6 +21,8 @@ public struct APIDescription: APIDescriptionType { } } +extension APIDescription: Sendable where Meta: Sendable {} + /// Can be used as `APIDescriptionType` for Documents that do not /// have any API Description (a.k.a. "JSON:API Object"). public struct NoAPIDescription: APIDescriptionType, CustomStringConvertible { @@ -33,6 +35,8 @@ public struct NoAPIDescription: APIDescriptionType, CustomStringConvertible { public var description: String { return "No JSON:API Object" } } +extension NoAPIDescription: Sendable {} + extension APIDescription { private enum CodingKeys: String, CodingKey { case version diff --git a/Sources/JSONAPI/Document/Document.swift b/Sources/JSONAPI/Document/Document.swift index 3673493..402cc6e 100644 --- a/Sources/JSONAPI/Document/Document.swift +++ b/Sources/JSONAPI/Document/Document.swift @@ -186,6 +186,10 @@ public struct Document(_ other: Document.Body.Data, combiningMetaWith metaMerge: (MetaType, MetaType) -> MetaType, diff --git a/Sources/JSONAPI/Document/Includes.swift b/Sources/JSONAPI/Document/Includes.swift index b76225e..8eb5000 100644 --- a/Sources/JSONAPI/Document/Includes.swift +++ b/Sources/JSONAPI/Document/Includes.swift @@ -45,6 +45,8 @@ public struct Includes: Encodable, Equatable { } } +extension Includes: Sendable where I: Sendable {} + extension Includes: Decodable where I: Decodable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() diff --git a/Sources/JSONAPI/Document/ResourceBody.swift b/Sources/JSONAPI/Document/ResourceBody.swift index 0986a4f..88b8d44 100644 --- a/Sources/JSONAPI/Document/ResourceBody.swift +++ b/Sources/JSONAPI/Document/ResourceBody.swift @@ -65,6 +65,8 @@ public struct SingleResourceBody: Equatable, Coda } } +extension Link: Sendable where Meta: Sendable, URL: Sendable {} + extension Link where Meta == NoMetadata { public init(url: URL) { self.init(url: url, meta: .none) diff --git a/Sources/JSONAPI/Meta/Meta.swift b/Sources/JSONAPI/Meta/Meta.swift index 7018cd6..51aec42 100644 --- a/Sources/JSONAPI/Meta/Meta.swift +++ b/Sources/JSONAPI/Meta/Meta.swift @@ -21,7 +21,7 @@ extension Optional: Meta where Wrapped: Meta {} /// Use this type when you want to specify not to encode or decode any metadata /// for a type. -public struct NoMetadata: Meta, CustomStringConvertible { +public struct NoMetadata: Meta, CustomStringConvertible, Sendable { public static var none: NoMetadata { return NoMetadata() } public init() { } diff --git a/Sources/JSONAPI/Resource/Attribute.swift b/Sources/JSONAPI/Resource/Attribute.swift index 5b0ed41..e39b884 100644 --- a/Sources/JSONAPI/Resource/Attribute.swift +++ b/Sources/JSONAPI/Resource/Attribute.swift @@ -34,6 +34,8 @@ public struct TransformedAttribute { // If we are using the identity transform, we can skip the transform and guarantee no // error is thrown. @@ -82,6 +84,8 @@ public struct Attribute: AttributeType { } } +extension Attribute: Sendable where RawValue: Sendable {} + extension Attribute: CustomStringConvertible { public var description: String { return "Attribute<\(String(describing: RawValue.self))>(\(String(describing: value)))" diff --git a/Sources/JSONAPI/Resource/Id.swift b/Sources/JSONAPI/Resource/Id.swift index fd05123..d8a727c 100644 --- a/Sources/JSONAPI/Resource/Id.swift +++ b/Sources/JSONAPI/Resource/Id.swift @@ -97,6 +97,8 @@ public struct Id: Equa } } +extension Id: Sendable where RawType: Sendable {} + extension Id: Hashable where RawType: RawIdType { public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(Self.self)) diff --git a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift index 95f04a7..ef2a340 100644 --- a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift +++ b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift @@ -15,7 +15,7 @@ import Poly /// disparate types under one roof for /// the purposes of JSON API compliant /// encoding or decoding. -public typealias EncodableJSONPoly = Poly & EncodablePrimaryResource & Sendable +public typealias EncodableJSONPoly = Poly & EncodablePrimaryResource public typealias EncodablePolyWrapped = Encodable & Equatable public typealias CodablePolyWrapped = EncodablePolyWrapped & Decodable diff --git a/Sources/JSONAPI/Resource/Relationship.swift b/Sources/JSONAPI/Resource/Relationship.swift index 4a2c3fa..bccf453 100644 --- a/Sources/JSONAPI/Resource/Relationship.swift +++ b/Sources/JSONAPI/Resource/Relationship.swift @@ -60,6 +60,12 @@ public struct ToOneRelationship let age: Attribute let favoriteColor: Attribute } - struct Relationships: JSONAPI.Relationships { + struct Relationships: JSONAPI.Relationships & Sendable { let bestFriend: ToOneRelationship let parents: ToManyRelationship } From 1e6b5312f323b0247570e7126c9ae7e76194b400 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sat, 13 Sep 2025 17:51:22 -0500 Subject: [PATCH 33/33] fixing test types --- .../Comparisons/DocumentCompareTests.swift | 4 ++-- .../Test Helpers/String+CreatableRawIdType.swift | 2 +- Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift | 2 +- Tests/JSONAPITests/Error/GenericJSONAPIErrorTests.swift | 2 +- .../JSONAPITests/Test Helpers/String+CreatableRawIdType.swift | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Tests/JSONAPITestingTests/Comparisons/DocumentCompareTests.swift b/Tests/JSONAPITestingTests/Comparisons/DocumentCompareTests.swift index dd05fe3..a06c7d8 100644 --- a/Tests/JSONAPITestingTests/Comparisons/DocumentCompareTests.swift +++ b/Tests/JSONAPITestingTests/Comparisons/DocumentCompareTests.swift @@ -143,7 +143,7 @@ fileprivate typealias TestType2 = ResourceObject, NoMetadata, NoLinks, Include2, NoAPIDescription, BasicJSONAPIError> -fileprivate struct TestMetadata: JSONAPI.Meta, CustomStringConvertible { +fileprivate struct TestMetadata: JSONAPI.Meta, CustomStringConvertible, Sendable { let total: Int var description: String { @@ -151,7 +151,7 @@ fileprivate struct TestMetadata: JSONAPI.Meta, CustomStringConvertible { } } -fileprivate struct TestLinks: JSONAPI.Links { +fileprivate struct TestLinks: JSONAPI.Links, Sendable { let link: Link } diff --git a/Tests/JSONAPITestingTests/Test Helpers/String+CreatableRawIdType.swift b/Tests/JSONAPITestingTests/Test Helpers/String+CreatableRawIdType.swift index dd3c8f7..282325a 100644 --- a/Tests/JSONAPITestingTests/Test Helpers/String+CreatableRawIdType.swift +++ b/Tests/JSONAPITestingTests/Test Helpers/String+CreatableRawIdType.swift @@ -7,7 +7,7 @@ import JSONAPI -private var uniqueStringCounter = 0 +nonisolated(unsafe) private var uniqueStringCounter = 0 extension String: CreatableRawIdType { public static func unique() -> String { diff --git a/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift b/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift index 0100a07..8783794 100644 --- a/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift +++ b/Tests/JSONAPITests/Document/DocumentDecodingErrorTests.swift @@ -224,7 +224,7 @@ extension DocumentDecodingErrorTests { case unknownError case basic(BasicError) - struct BasicError: Codable, Equatable { + struct BasicError: Codable, Equatable, Sendable { let code: Int let description: String } diff --git a/Tests/JSONAPITests/Error/GenericJSONAPIErrorTests.swift b/Tests/JSONAPITests/Error/GenericJSONAPIErrorTests.swift index d645c23..6f095cc 100644 --- a/Tests/JSONAPITests/Error/GenericJSONAPIErrorTests.swift +++ b/Tests/JSONAPITests/Error/GenericJSONAPIErrorTests.swift @@ -132,7 +132,7 @@ final class GenericJSONAPIErrorTests: XCTestCase { } } -private struct TestPayload: Codable, Equatable, ErrorDictType { +private struct TestPayload: Codable, Equatable, ErrorDictType, Sendable { let hello: String let world: Int? diff --git a/Tests/JSONAPITests/Test Helpers/String+CreatableRawIdType.swift b/Tests/JSONAPITests/Test Helpers/String+CreatableRawIdType.swift index dd3c8f7..282325a 100644 --- a/Tests/JSONAPITests/Test Helpers/String+CreatableRawIdType.swift +++ b/Tests/JSONAPITests/Test Helpers/String+CreatableRawIdType.swift @@ -7,7 +7,7 @@ import JSONAPI -private var uniqueStringCounter = 0 +nonisolated(unsafe) private var uniqueStringCounter = 0 extension String: CreatableRawIdType { public static func unique() -> String {