Skip to content

Commit

Permalink
Make requests idempotent
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurentTreguier committed Sep 6, 2024
1 parent b68ffd6 commit 707dcc3
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 2 deletions.
12 changes: 10 additions & 2 deletions Fyreplace/Config/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,18 @@ struct Config {
}

func client(for environment: ServerEnvironment) -> Client {
let configuration = URLSessionConfiguration.default
configuration.waitsForConnectivity = true

#if os(iOS)
configuration.multipathServiceType = .handover
#endif

return Client(
serverURL: url(for: environment),
transport: URLSessionTransport(),
middlewares: [AuthenticationMiddleware()]
configuration: .init(dateTranscoder: .iso8601WithFractionalSeconds),
transport: URLSessionTransport(configuration: .init(session: .init(configuration: configuration))),
middlewares: [RequestIdMiddleware(), AuthenticationMiddleware()]
)
}
}
Expand Down
17 changes: 17 additions & 0 deletions Fyreplace/Data/RequestIdMiddleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Foundation
import HTTPTypes
import OpenAPIRuntime

struct RequestIdMiddleware: ClientMiddleware {
func intercept(
_ request: HTTPRequest,
body: HTTPBody?,
baseURL: URL,
operationID _: String,
next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
) async throws -> (HTTPResponse, HTTPBody?) {
var request = request
request.headerFields[.xRequestId] = UUID().uuidString
return try await next(request, body, baseURL)
}
}
5 changes: 5 additions & 0 deletions Fyreplace/Extensions/HTTPField.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import HTTPTypes

extension HTTPField.Name {
static let xRequestId = Self("X-Request-Id")!
}
7 changes: 7 additions & 0 deletions Fyreplace/Extensions/String.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Foundation

extension String {
static var randomUuid: String {
UUID().uuidString
}
}

0 comments on commit 707dcc3

Please sign in to comment.