Skip to content

Commit

Permalink
feat: Disable server mutations per/request basis (#88)
Browse files Browse the repository at this point in the history
Co-authored-by: danthorpe <[email protected]>
  • Loading branch information
danthorpe and danthorpe authored Jul 3, 2024
1 parent 5dfb357 commit ff0e99f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
29 changes: 28 additions & 1 deletion Sources/Networking/Components/Server/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,36 @@ extension NetworkingComponent {
}
}

struct MutateRequest: NetworkingModifier {
// MARK: - Option to opt out of Server based mutations

/// A `HTTPRequestDataOption` which is used to determine whether "server mutations"
/// will impact a specific `HTTPRequestData`.
///
/// Server mutations are networking modifiers added to the stack by using
/// the `.server()` APIs. Their purpose is to set properties of every request
/// which is sent, such as the server authority.
///
/// However, in some cases, it is useful to be able to bypass all of these
/// modifications, and send the request exactly as specified. To do this,
/// set the option to `.disabled`.
public enum ServerMutationsOption: HTTPRequestDataOption {
public static let defaultOption: Self = .enabled
case enabled
case disabled
}

extension HTTPRequestData {
public var serverMutations: ServerMutationsOption {
get { self[option: ServerMutationsOption.self] }
set { self[option: ServerMutationsOption.self] = newValue }
}
}

private struct MutateRequest: NetworkingModifier {
let mutate: @Sendable (inout HTTPRequestData) -> Void

func resolve(upstream: some NetworkingComponent, request: HTTPRequestData) -> HTTPRequestData {
guard case .enabled = request.serverMutations else { return request }
var copy = request
mutate(&copy)
return copy
Expand Down
18 changes: 18 additions & 0 deletions Tests/NetworkingTests/Components/ServerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,22 @@ final class ServerTests: NetworkingTestCase {

XCTAssertNoDifference(sentRequestsURL, URL(static: "https://example.com/?message=hello%2Bworld"))
}

func test__set_server_mutation_option__disabled() async throws {
let reporter = TestReporter()

let network = TerminalNetworkingComponent()
.mocked(.ok(), check: { _ in true })
.reported(by: reporter)
.server(authority: "sample.com")
.logged(using: Logger())

var request = HTTPRequestData(authority: "api-sample.com", path: "auth")
request.serverMutations = .disabled

try await network.data(request)
let sentRequests = await reporter.requests
XCTAssertEqual(sentRequests.map(\.authority), ["api-sample.com"])
XCTAssertEqual(sentRequests.map(\.path), ["/auth"])
}
}

0 comments on commit ff0e99f

Please sign in to comment.