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.
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()
Add to the Package.swift
:
dependencies: [
.package(
url: "https://github.com/BenShutt/DataRequest.git",
branch: "main"
)
]
- The
URLRequestMaker
checks for conformance ofRequestBody
and adds the HTTP body accordingly - A
DecodableRequest
is aURLRequestMaker
with the configuration properties of a data request defaulted
Since URLRequestMaker
conforms to URLRequestConvertible
you can use Alamofire directly:
AF.upload(data, with: Endpoint())
.uploadProgress { progress in ... }
.decodeValue()
where Endpoint
is some URLRequestMaker
.
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
.