Skip to content

Commit

Permalink
feature: urlsession을 이용한 서버통신 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
Jihyun247 committed Jul 24, 2024
1 parent 7eadf98 commit a12a5e9
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
//

import Foundation
import KeychainClientInterface

public protocol APIRequestLoaderInterface {
associatedtype T: TargetType

Check warning on line 13 in Projects/Core/APIClient/Interface/APIRequestLoaderInterface.swift

View workflow job for this annotation

GitHub Actions / Run Swiftlint

Type name 'T' should be between 3 and 40 characters long (type_name)
func fetchData<M: Decodable> (
target: TargetType,
responseData: M.Type
target: T,
responseData: M.Type,
keychainClient: KeychainClient
) async throws -> M
}
51 changes: 51 additions & 0 deletions Projects/Core/APIClient/Sources/APIRequestLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,54 @@
//

import Foundation
import APIClientInterface
import KeychainClientInterface

public class APIRequestLoader<T: TargetType>: 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<M: Decodable>(
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
}
}
}

0 comments on commit a12a5e9

Please sign in to comment.