-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
73 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// | ||
// APIProvider.swift | ||
// GsHometown-iOS | ||
// | ||
// Created by 한지석 on 5/21/24. | ||
// | ||
|
||
import Foundation | ||
|
||
import Moya | ||
|
||
final class APIProvider<T: TargetType>: MoyaProvider<T> { | ||
init() { | ||
let plugin: [PluginType] = [GsPlugin()] | ||
super.init(plugins: plugin) | ||
} | ||
|
||
func request<U: Codable>( | ||
_ object: U.Type, | ||
target: T, | ||
completion: @escaping (NetworkResult<U>) -> () | ||
) { | ||
request(target) { [weak self] result in | ||
guard let self = self else { | ||
completion(.networkFail) | ||
return | ||
} | ||
switch result { | ||
case .success(let response): | ||
let statusCode = response.statusCode | ||
let data = response.data | ||
let networkResult = self.judgeStatus(statusCode, | ||
data, | ||
object.self) | ||
completion(networkResult) | ||
case .failure: | ||
completion(.networkFail) | ||
} | ||
} | ||
} | ||
|
||
func judgeStatus<U: Codable>( | ||
_ statusCode: Int, | ||
_ data: Data, | ||
_ object: U.Type | ||
) -> NetworkResult<U> { | ||
switch statusCode { | ||
case 200..<205: | ||
return isVaildData(data, object) | ||
case 400..<500: | ||
return .requestErr | ||
case 500: | ||
return .serverErr | ||
default: | ||
return .networkFail | ||
} | ||
} | ||
|
||
private func isVaildData<U: Codable>( | ||
_ data: Data, | ||
_ object: U.Type | ||
) -> NetworkResult<U> { | ||
let decoder = JSONDecoder() | ||
guard let decodedData = try? decoder.decode( | ||
U.self, | ||
from: data | ||
) else { | ||
print("⛔️ \(self)애서 디코딩 오류가 발생했습니다 ⛔️") | ||
return .pathErr | ||
} | ||
return .success(decodedData) | ||
} | ||
} |