Member-only story
Mocking Async Requests with Factory
Strategies designed to make your network and service layer code easy to write, easy to test, and easy to preview.
10 min readMay 7, 2025
You can’t be a Swift developer without learning about protocols and their use in creating abstractions around common services.
public protocol UserServiceType: Sendable {
func load() async throws -> [User]
}
struct UserService: UserServiceType {
@Injected(\.sessionManager) private var session
public func load() async throws -> [User] {
try await session.request()
.add(path: "/api")
.add(queryItems: ["results" : "25", "seed": "998", "nat": "us"])
.data(type: UserResultType.self)
.results
}
}
This example is using Factory to inject our session manager into our UserService
, and constructing and executing the API query using RequestBuilder, but the same concepts apply no matter what dependency injection system you’re using, or no matter how you’re building the actual request.
Just to illustrate that, here’s a more traditional implementation.
struct RequestUsers: UserServiceType {
@Injected(\.session) private var session
func load() async throws -> [User] {
let request = try request()
let (data, _) =…