Persist auth across preview rerenders
This commit is contained in:
1 parent
d6b35fe346
commit
d9a996aa98
5 files changed
+163
-8
No files matched your search
@@ -66,6 +66,9 @@ public final class APIClient: @unchecked Sendable {
|
||||
config.httpShouldSetCookies = true
|
||||
self.session = URLSession(configuration: config)
|
||||
}
|
||||
if let cookieStorage = self.session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.restore(into: cookieStorage, for: configuration.apiBaseURL)
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
self.decoder = decoder
|
||||
@@ -105,6 +108,12 @@ public final class APIClient: @unchecked Sendable {
|
||||
}
|
||||
if !query.isEmpty { components.queryItems = query }
|
||||
guard let url = components.url else { throw APIError.invalidURL }
|
||||
if let cookieStorage = session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.restore(into: cookieStorage, for: url)
|
||||
if path.hasPrefix("auth/") {
|
||||
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "before \(path)")
|
||||
}
|
||||
}
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
@@ -119,6 +128,12 @@ public final class APIClient: @unchecked Sendable {
|
||||
}
|
||||
do {
|
||||
let (data, rawResponse) = try await session.data(for: request)
|
||||
if let cookieStorage = session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.save(from: cookieStorage, for: url)
|
||||
if path.hasPrefix("auth/") {
|
||||
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "after \(path)")
|
||||
}
|
||||
}
|
||||
guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse }
|
||||
guard (200..<300).contains(http.statusCode) else {
|
||||
let message =
|
||||
@@ -163,6 +178,11 @@ public final class APIClient: @unchecked Sendable {
|
||||
return try decoder.decode(Response.self, from: data)
|
||||
} catch { throw APIError.decoding(String(describing: error)) }
|
||||
} catch let error as APIError { throw error } catch {
|
||||
if Task.isCancelled || error is CancellationError
|
||||
|| (error as? URLError)?.code == .cancelled
|
||||
{
|
||||
throw CancellationError()
|
||||
}
|
||||
throw APIError.transport(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user