ComposableRequest

6.0.1

A Swift library to abstract API clients.
sbertix/ComposableRequest

What's New

v6.0.1

2021-08-27T20:12:29Z

Bug Fixes

  • add completion-based future (db7e6b5)

Header


Swift codecov
iOS macOS tvOS watchOS


ComposableRequest is a networking layer based on a declarative interface, written in (modern) Swift.

It abstracts away URLSession implementation (or your preferred custom networking library), in order to provide concise and powerful endpoint representations, supporting, out-of-the-box, completion handlers, Combine Publishers and structured concurrencty (async/await) with a single definition.

It comes with Storage (inside of Storage), a way of caching Storable items, and related concrete implementations (e.g. UserDefaultsStorage, KeychainStorage – for which you're gonna need to add StorageCrypto, depending on KeychainAccess, together with the ability to provide the final user of your API wrapper to inject code through Providers.

Status

push GitHub release (latest by date)

You can find all changelogs directly under every release.

What's next?

ComposableRequest was initially Swiftagram's networking layer and it still tends to follow roughly the same development cycle.

Milestones, issues, are the best way to keep updated with active developement.

Feel free to contribute by sending a pull request. Just remember to refer to our guidelines and Code of Conduct beforehand.

Installation

Swift Package Manager (Xcode 11 and above)

  1. Select File/Swift Packages/Add Package Dependency… from the menu.
  2. Paste https://github.com/sbertix/ComposableRequest.git.
  3. Follow the steps.
  4. Add Storage together with Requests for the full experience.

Why not CocoaPods, or Carthage, or blank?

Supporting multiple dependency managers makes maintaining a library exponentially more complicated and time consuming.
Furthermore, with the integration of the Swift Package Manager in Xcode 11 and greater, we expect the need for alternative solutions to fade quickly.

Targets

  • Requests, an HTTP client originally integrated in Swiftagram, the core library.
  • Storage
  • StorageCrypto, depending on KeychainAccess, can be imported together with Storage to extend its functionality.

Usage

Check out Swiftagram or visit the (auto-generated) documentation for Requests, Storage and StorageCrypto to learn about use cases.

Endpoint

As an implementation example, we can display some code related to the Instagram endpoint tasked with deleting a post.

public extension Request {
    /// An enum listing an error.
    enum DeleteError: Swift.Error { case invalid }
    
    /// Delete one of your own posts, matching `identifier`.
    /// Checkout https://github.com/sbertix/Swiftagram for more info.
    ///
    /// - parameter identifier: String
    /// - returns: A locked `AnyObservable`, waiting for authentication `HTTPCookie`s.
    func delete<R: Requester>(_ identifier: String) -> Providers.LockRequester<[HTTPCookie], R, R.Requested<Bool>> {
        // Wait for user defined values.
        .init { cookies, requester in
            // Fetch first info about the post to learn if it's a video or picture
            // as they have slightly different endpoints for deletion.
            Request("https://i.instagram.com/api/v1/media")
                .path(appending: identifier)
                .info   // Equal to `.path(appending: "info")`.
                // Wait for the user to `inject` an array of `HTTPCookie`s.
                // You should implement your own `model` to abstract away
                // authentication cookies, but as this is just an example
                // we leave it to you.
                .header(appending: HTTPCookie.requestHeaderFields(with: cookies))
                // Prepare for the actual request.
                .prepare(with: requester)
                // Check it returned a valid media.
                .map(\.data)
                // Decode it inside a `Wrapper`, allowing to interrogate JSON
                // representations of object without knowing them in advance.
                // (It's literally the missing `AnyCodable`).
                .decode()
                // Switch to a new request.
                .switch { wrapper throws -> R.Requested<Bool> in
                    guard let type = wrapper["items"][0].mediaType.int(),
                          [1, 2, 8].contains(type) else {
                        throw DeleteError.invalid
                    }
                    // Actually delete it now that we have all data.
                    return Request("https://i.instagram.com/api/v1/media")
                        .path(appending: identifier)
                        .path(appending: "delete/")
                        .query(appending: type == 2 ? "VIDEO" : "PHOTO", forKey: "media_type")
                        // This will be applied exactly as before, but you can add whaterver
                        // you need to it, as it will only affect this `Request`.
                        .header(appending: HTTPCookie.requestHeaderFields(with: cookies))
                        // Create the `Publisher`.
                        .prepare(with: requester)
                        .map(\.data)
                        .decode()
                        .map { $0.status == "ok" }
                        .requested(by: requester)
                }
                .requested(by: requester)
        }
    }
}

How can the user then retreieve the information?

All the user has to do is…

/// A valid post identifier.
let identifier: String = /* a valid String */
/// A valid array of cookies.
let cookies: [HTTPCookie] = /* an array of HTTPCookies */
/// A *retained* collection of `AnyCancellable`s.
var bin: Set<AnyCancellable> = []

/// Delete it using completion handlers.
Request.delete(identifier)
    .unlock(with: cookies)
    .prepare(with: URLSessionCompletionRequester(session: .shared))
    .onSuccess { _ in } onFailure: { _ in }
    .resume()
    
[]

/// Delete it using **Combine**.
Request.delete(identifier)
    .unlock(with: cookies)
    .prepare(with: URLSessionCombineRequester(session: .shared))    
    .sink { _ in } receiveValue: { print($0) }
    .store(in: &bin)

[]

/// Delete it using _async/await_.
let result = try await Request.delete(identifier)
    .unlock(with: cookies)
    .prepare(with: .async(session: .shared))

Resume and cancel requests

What about cancelling the request, or starting it a later date?

Concrete implementation of Receivable might implement suspension and cancellation through their underlying types (like URLSessionDataTask or Cancellable).

Caching

Caching of Storables is provided through conformance to the Storage protocol, specifically by implementing either ThrowingStorage or NonThrowingStorage.

The library comes with several concrete implementations.

  • TransientStorage should be used when no caching is necessary, and it's what Authenticators default to when no Storage is provided.
  • UserDefaultsStorage allows for faster, out-of-the-box, testing, although it's not recommended for production as private cookies are not encrypted.
  • KeychainStorage, requiring you to add ComposableStorageCrypto, (preferred) stores them safely in the user's keychain.
    -->

Description

  • Swift Tools 5.2.0
View More Packages from this Author

Dependencies

Last updated: Sat Oct 01 2022 15:36:45 GMT-0500 (GMT-05:00)