-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNetworkService.swift
More file actions
100 lines (84 loc) · 2.63 KB
/
NetworkService.swift
File metadata and controls
100 lines (84 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// NetworkService.swift
// NetworkService
//
// Created by 최정인 on 6/19/25.
//
import Foundation
import Shared
final class NetworkService {
static let shared = NetworkService()
private let decoder = JSONDecoder()
private let plugins: [NetworkPlugin]
private let maxRetryCount = 1
private init() {
plugins = [
TokenInjectionPlugin(),
RefreshTokenPlugin(),
RetryPlugin(),
BitnagilLoggingPlugin()]
}
func request<T: Decodable>(
endpoint: Endpoint,
type: T.Type,
withPlugins: Bool = true
) async throws -> T? {
var retryCount = 0
while true {
do {
return try await performRequest(
endpoint: endpoint,
type: type,
withPlugins: withPlugins)
} catch let error as NetworkError {
guard
error == .needRetry,
retryCount < maxRetryCount
else { throw error }
retryCount += 1
continue
}
}
}
private func performRequest<T: Decodable>(
endpoint: Endpoint,
type: T.Type,
withPlugins: Bool = true
) async throws -> T? {
var request = try endpoint.makeURLRequest()
if withPlugins {
for plugin in plugins {
request = try await plugin.willSend(request: request, endpoint: endpoint)
}
}
let (data, response) = try await URLSession.shared.data(for: request)
if withPlugins {
for plugin in plugins {
try await plugin.didReceive(
response: response,
data: data,
endpoint: endpoint)
}
}
guard let httpResponse = response as? HTTPURLResponse
else { throw NetworkError.invalidResponse }
guard 200..<300 ~= httpResponse.statusCode else {
throw NetworkError.invalidStatusCode(statusCode: httpResponse.statusCode)
}
if T.self == EmptyResponseDTO.self {
return EmptyResponseDTO() as? T
}
do {
let bitnagilResponse = try decoder.decode(BaseResponse<T>.self, from: data)
guard let responseDTO = bitnagilResponse.data else { return nil }
return responseDTO
} catch {
do {
let generalResponse = try decoder.decode(T.self, from: data)
return generalResponse
} catch {
throw NetworkError.decodingError
}
}
}
}