From a12a5e9e9927a970f856e9f3d8e7182fbff4db5a Mon Sep 17 00:00:00 2001 From: Jihyun247 Date: Wed, 24 Jul 2024 22:47:15 +0900 Subject: [PATCH] =?UTF-8?q?feature:=20urlsession=EC=9D=84=20=EC=9D=B4?= =?UTF-8?q?=EC=9A=A9=ED=95=9C=20=EC=84=9C=EB=B2=84=ED=86=B5=EC=8B=A0=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Interface/APIRequestLoaderInterface.swift | 7 ++- .../APIClient/Sources/APIRequestLoader.swift | 51 +++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/Projects/Core/APIClient/Interface/APIRequestLoaderInterface.swift b/Projects/Core/APIClient/Interface/APIRequestLoaderInterface.swift index eaf7251..99d2ed7 100644 --- a/Projects/Core/APIClient/Interface/APIRequestLoaderInterface.swift +++ b/Projects/Core/APIClient/Interface/APIRequestLoaderInterface.swift @@ -7,10 +7,13 @@ // import Foundation +import KeychainClientInterface public protocol APIRequestLoaderInterface { + associatedtype T: TargetType func fetchData ( - target: TargetType, - responseData: M.Type + target: T, + responseData: M.Type, + keychainClient: KeychainClient ) async throws -> M } diff --git a/Projects/Core/APIClient/Sources/APIRequestLoader.swift b/Projects/Core/APIClient/Sources/APIRequestLoader.swift index fe8bb84..46b864c 100644 --- a/Projects/Core/APIClient/Sources/APIRequestLoader.swift +++ b/Projects/Core/APIClient/Sources/APIRequestLoader.swift @@ -7,3 +7,54 @@ // import Foundation +import APIClientInterface +import KeychainClientInterface + +public class APIRequestLoader: APIRequestLoaderInterface { + let coniguration: URLSessionConfiguration + let session: URLSession + + public init(configuration: URLSessionConfiguration = .default) { + self.coniguration = configuration +#if PROD + self.session = URLSession(configuration: configuration) +#elseif DEV + let sessionDelegate = EventLoggerDelegate() + self.session = URLSession(configuration: configuration, delegate: sessionDelegate) +#endif + + // TODO: token interceptor + } + + public func fetchData( + target: T, + responseData: M.Type, + keychainClient: KeychainClient + ) async throws -> M { + let urlRequest = try await target.asURLRequest(keychainClient: keychainClient) + + let (data, response) = try await session.data(for: urlRequest) + + guard let httpResponse = response as? HTTPURLResponse else { + throw NetworkError.noResponseError + } + + switch httpResponse.statusCode { + case 200..<300: + do { + let decodedData = try JSONDecoder().decode(responseData, from: data) + return decodedData + } catch { + throw NetworkError.decodingError + } + case 401: // token interceptor 예정 + throw NetworkError.authorizationError + case 400..<500: + throw NetworkError.requestError("bad request") + case 500..<600: + throw NetworkError.serverError + default: + throw NetworkError.unknownError + } + } +}