Просмотр исходного кода

[WIP] Added ResponseAdapter protocol to RequestInterceptor

Christian Noon 4 лет назад
Родитель
Сommit
85067cbd3c
2 измененных файлов с 30 добавлено и 2 удалено
  1. 19 1
      Source/Request.swift
  2. 11 1
      Source/RequestInterceptor.swift

+ 19 - 1
Source/Request.swift

@@ -120,6 +120,9 @@ public class Request {
         /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
         /// representation in the state machine in the future.
         var isFinishing = false
+
+        /// TBD
+        var adaptedResponse: HTTPURLResponse?
     }
 
     /// Protected `MutableState` value that provides thread-safe access to state values.
@@ -209,7 +212,7 @@ public class Request {
 
     /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
     /// last `URLSessionTask`.
-    public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
+    public var response: HTTPURLResponse? { mutableState.adaptedResponse ?? lastTask?.response as? HTTPURLResponse }
 
     // MARK: Tasks
 
@@ -466,6 +469,21 @@ public class Request {
 
         self.error = self.error ?? error
 
+        /// Adapt the response if there's an interceptor attached to the request
+        if
+            let interceptor = interceptor,
+            let response = task.response as? HTTPURLResponse,
+            let request = task.originalRequest
+        {
+            do {
+                let response = try interceptor.adapt(response, for: request)
+                $mutableState.write { $0.adaptedResponse = response }
+            } catch {
+                /// NOTE: This should be a `responseAdaptationFailed` error
+                self.error = AFError.requestAdaptationFailed(error: error)
+            }
+        }
+
         validators.forEach { $0() }
 
         eventMonitor?.request(self, didCompleteTask: task, with: error)

+ 11 - 1
Source/RequestInterceptor.swift

@@ -89,8 +89,14 @@ public protocol RequestRetrier {
 
 // MARK: -
 
+public protocol ResponseAdapter {
+    func adapt(_ response: HTTPURLResponse, for request: URLRequest) throws -> HTTPURLResponse
+}
+
+// MARK: -
+
 /// Type that provides both `RequestAdapter` and `RequestRetrier` functionality.
-public protocol RequestInterceptor: RequestAdapter, RequestRetrier {}
+public protocol RequestInterceptor: RequestAdapter, RequestRetrier, ResponseAdapter {}
 
 extension RequestInterceptor {
     public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
@@ -103,6 +109,10 @@ extension RequestInterceptor {
                       completion: @escaping (RetryResult) -> Void) {
         completion(.doNotRetry)
     }
+
+    public func adapt(_ response: HTTPURLResponse, for request: URLRequest) throws -> HTTPURLResponse {
+        response
+    }
 }
 
 /// `RequestAdapter` closure definition.