-
Notifications
You must be signed in to change notification settings - Fork 351
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Change private to internal for generateHeaders() visbility modifier t…
…o enable future extension and/or testing.
- Loading branch information
Showing
2 changed files
with
44 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// | ||
// URLSessionDataTaskManager.swift | ||
// | ||
// | ||
// Created by Benjamin Truitt on 7/29/23. | ||
// | ||
|
||
import Foundation | ||
|
||
public class URLSessionDataTaskManager { | ||
|
||
private var session: URLSessionProtocol | ||
|
||
init(session: URLSessionProtocol) { | ||
self.session = session | ||
} | ||
|
||
func performDataTask<ResultType: Codable>(with request: URLRequest, completion: @escaping (Result<ResultType, Error>) -> Void) { | ||
let task = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in | ||
if let error = error { | ||
completion(.failure(error)) | ||
} else if let data = data { | ||
do { | ||
let decoded = try JSONDecoder().decode(ResultType.self, from: data) | ||
completion(.success(decoded)) | ||
} catch { | ||
do { | ||
let decoded = try JSONDecoder().decode(APIErrorResponse.self, from: data) | ||
completion(.failure(decoded)) | ||
} catch let decodingError { | ||
completion(.failure(decodingError)) | ||
} | ||
} | ||
} else { | ||
completion(.failure(OpenAIError.emptyData)) | ||
} | ||
} | ||
task.resume() | ||
} | ||
} |