diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2e0ea6f..df8f649 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,34 +13,21 @@ 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:6.0 + - swift:6.1 container: ${{ matrix.image }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v5 - 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@v5 - name: Run tests run: swift test --enable-test-discovery diff --git a/JSONAPI.podspec b/JSONAPI.podspec deleted file mode 100644 index 5cf8785..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.0.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.4.0" - -end diff --git a/Package.resolved b/Package.resolved index 63465c7..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": "36ba3f624bffa34f5f9b9c7648eab3cfdcab4748", - "version": "2.5.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 3762356..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.4.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 878fcdf..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/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 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. @@ -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) @@ -60,38 +58,18 @@ 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.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' +.package(url: "https://github.com/mattpolzin/JSONAPI.git", from: "6.0.0") ``` -### 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/client-server-example.md) +- [Server & Client Example](./documentation/examples/client-server-example.md) - [Usage Documentation](./documentation/usage.md) # JSONAPI+Testing 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/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/Document.swift b/Sources/JSONAPI/Document/Document.swift index da0a37f..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, combiningLinksWith linksMerge: (LinksType, LinksType) -> LinksType) -> Document.Body.Data { return Document.Body.Data(primary: primary.appending(other.primary), @@ -272,10 +287,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 .init(primary: primary.appending(other.primary), + includes: includes.appending(other.includes), + meta: other.meta, + links: other.links) } } diff --git a/Sources/JSONAPI/Document/DocumentDecodingError.swift b/Sources/JSONAPI/Document/DocumentDecodingError.swift index 2bcfa60..8a96054 100644 --- a/Sources/JSONAPI/Document/DocumentDecodingError.swift +++ b/Sources/JSONAPI/Document/DocumentDecodingError.swift @@ -33,6 +33,14 @@ 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."): + self = .primaryResourceMissing default: return nil } @@ -71,3 +79,6 @@ extension DocumentDecodingError: CustomStringConvertible { } } } + +private protocol _ArrayType {} +extension Array: _ArrayType {} diff --git a/Sources/JSONAPI/Document/Includes.swift b/Sources/JSONAPI/Document/Includes.swift index e48a547..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() @@ -206,6 +208,38 @@ 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: - 14 includes +public typealias Include14 = Poly14 +extension Includes where I: _Poly14 { + public subscript(_ lookup: I.N.Type) -> [I.N] { + return values.compactMap(\.n) + } +} + +// 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/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: 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/Meta/Links.swift b/Sources/JSONAPI/Meta/Links.swift index ab2b7e1..bbe7335 100644 --- a/Sources/JSONAPI/Meta/Links.swift +++ b/Sources/JSONAPI/Meta/Links.swift @@ -9,7 +9,7 @@ public protocol Links: Codable, Equatable {} /// Use NoLinks where no links should belong to a JSON API component -public struct NoLinks: Links, CustomStringConvertible { +public struct NoLinks: Links, CustomStringConvertible, Sendable { public static var none: NoLinks { return NoLinks() } public init() {} @@ -28,6 +28,8 @@ public struct Link: 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 2fc4bac..d8a727c 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" } @@ -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 73c1246..ef2a340 100644 --- a/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift +++ b/Sources/JSONAPI/Resource/Poly+PrimaryResource.swift @@ -20,7 +20,7 @@ public typealias EncodableJSONPoly = Poly & EncodablePrimaryResource 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 {} @@ -162,3 +164,139 @@ 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 {} + +// 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 {} + +// 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/Sources/JSONAPI/Resource/Relationship.swift b/Sources/JSONAPI/Resource/Relationship.swift index fc03c4e..bccf453 100644 --- a/Sources/JSONAPI/Resource/Relationship.swift +++ b/Sources/JSONAPI/Resource/Relationship.swift @@ -60,6 +60,12 @@ public struct ToOneRelationship PrimaryResourceBodyComparison { guard let one = testableResourceObject, let two = other.testableResourceObject else { 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) { 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/Comparisons/IncludesCompareTests.swift b/Tests/JSONAPITestingTests/Comparisons/IncludesCompareTests.swift index b25dd11..bd5ca90 100644 --- a/Tests/JSONAPITestingTests/Comparisons/IncludesCompareTests.swift +++ b/Tests/JSONAPITestingTests/Comparisons/IncludesCompareTests.swift @@ -224,13 +224,13 @@ private typealias TestType1 = ResourceObject let age: Attribute let favoriteColor: Attribute } - struct Relationships: JSONAPI.Relationships { + struct Relationships: JSONAPI.Relationships & Sendable { let bestFriend: ToOneRelationship let parents: ToManyRelationship } 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 a10d45f..8783794 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 } @@ -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/Document/DocumentTests.swift b/Tests/JSONAPITests/Document/DocumentTests.swift index d6058ec..559a257 100644 --- a/Tests/JSONAPITests/Document/DocumentTests.swift +++ b/Tests/JSONAPITests/Document/DocumentTests.swift @@ -1528,6 +1528,25 @@ 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) + XCTAssertEqual(combined.meta, bodyData2.meta) + XCTAssertEqual(combined.links, bodyData2.links) + } + 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) 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/Includes/IncludeTests.swift b/Tests/JSONAPITests/Includes/IncludeTests.swift index 6da21e5..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) @@ -219,6 +229,104 @@ 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) + } + + 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) + } + + 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 @@ -536,4 +644,94 @@ 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 + + enum TestEntityType14: ResourceObjectDescription { + + typealias Attributes = NoAttributes + + public static var jsonType: String { return "test_entity14" } + + typealias Relationships = NoRelationships + } + + typealias TestEntity14 = BasicEntity + + enum TestEntityType15: ResourceObjectDescription { + + typealias Attributes = NoAttributes + + public static var jsonType: String { return "test_entity15" } + + typealias Relationships = NoRelationships + } + + 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) + } + } } diff --git a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift index 708e154..df47120 100644 --- a/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift +++ b/Tests/JSONAPITests/Includes/stubs/IncludeStubs.swift @@ -687,6 +687,402 @@ 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 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 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 = """ [ diff --git a/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift b/Tests/JSONAPITests/ResourceObject/ResourceObjectDecodingErrorTests.swift index 6597293..694acb9 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." + ) + } } } @@ -440,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."# ) } } @@ -450,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. the 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. the JSON:API type name) is not a String as expected." + ) + } } } } 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" } 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) 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 { 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)!)") +``` +