Skip to content

Commit

Permalink
Добавлен responseTuner
Browse files Browse the repository at this point in the history
  • Loading branch information
Oleg Bakharev committed Mar 27, 2024
1 parent 0075f72 commit 95c0677
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
4 changes: 4 additions & 0 deletions Sources/AsyncHttpClient/AsyncHttpClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ public enum AsyncHttpRequestTuners {
/// Тюнер запроса - позволяет как угодно настроить запрос
case request((inout URLRequest) -> Void)

/// Тюнер ответа - позволяет валидировать и извлекать данные из заголовка ответа
case response((HTTPURLResponse) throws -> Void)

/// Тюнер кодера. Позволяет кастомизировать кодер
case encoder((inout JSONEncoder) -> Void)

Expand All @@ -16,6 +19,7 @@ public enum AsyncHttpRequestTuners {

public enum Keys {
case request
case response
case encoder
case decoder
}
Expand Down
13 changes: 9 additions & 4 deletions Sources/AsyncHttpClient/AsyncHttpJsonClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,16 @@ public class AsyncHttpJsonClient: AsyncHttpClient {
throw URLError.emptyResponse
}

guard let response = response as? HTTPURLResponse else {
throw URLError.invalidResponse
}

try validate(response, data: data)

if case .response(let responseTuner) = tuners[.response] {
try responseTuner(response)
}

do {
var decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
Expand All @@ -276,10 +284,7 @@ public class AsyncHttpJsonClient: AsyncHttpClient {
}
}

private func validate(_ response: URLResponse, data: Data?) throws {
guard let response = response as? HTTPURLResponse else {
throw URLError.invalidResponse
}
private func validate(_ response: HTTPURLResponse, data: Data?) throws {
if let responseValidator {
try responseValidator.validate(response: response, data: data)
} else if data?.count ?? 0 == 0 || response.isError {
Expand Down

0 comments on commit 95c0677

Please sign in to comment.