Skip to content

Modularization of data requests using Alamofire with concurrency

Notifications You must be signed in to change notification settings

BenShutt/DataRequest

Repository files navigation

DataRequest

Modularization of data requests using Alamofire with concurrency.

This package encourages a design pattern where the configuration of an endpoint is encapsulated into the properties of a structure. A similar design to a SwiftUI View. It adds rather than replaces; direct use of Alamofire (or vanilla URLSession) is still encouraged. There is also some helpful shorthand.

Example Usage

Define a decodable model returned in a response:

struct Model: Decodable { ... }

Specify the configuration of the request endpoint:

struct GetModel: DecodableRequest {
    typealias ResponseBody = Model

    var urlComponents: URLComponents {
        ...
    }
}

Finally, execute the request in an asynchronous environment:

let model = try await GetModel().request()

Installation

Add to the Package.swift:

dependencies: [
    .package(
        url: "https://github.com/BenShutt/DataRequest.git",
        branch: "main"
    )
]

Notes

  • The URLRequestMaker checks for conformance of RequestBody and adds the HTTP body accordingly
  • A DecodableRequest is a URLRequestMaker with the configuration properties of a data request defaulted

Uploads

Since URLRequestMaker conforms to URLRequestConvertible you can use Alamofire directly:

AF.upload(data, with: Endpoint())
    .uploadProgress { progress in ... }
    .decodeValue()

where Endpoint is some URLRequestMaker.

Debug Logging

To log request/responses, make a new Session instance (managing its lifecycle accordingly) with a ResponseEventMonitor event monitor. The ResponseEventMonitor logs the debugDescription of the DataResponse. For example:

extension Session {
    static let debug = Session(eventMonitors: [
        ResponseEventMonitor()
    ])
}

This can be returned in the session property of the DecodableRequest.

About

Modularization of data requests using Alamofire with concurrency

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages