Skip to content

Commit f74f6f8

Browse files
authored
Обновление сетевого слоя - 1 (#260)
* В процессе (#254) * В процессе (#254) * В процессе - Токен авторизации теперь настраивается только внутри `RequestComponents` - Убрал `needAuth` отовсюду: если токен есть, передаем его всегда
1 parent 38d0b2a commit f74f6f8

File tree

19 files changed

+749
-578
lines changed

19 files changed

+749
-578
lines changed

SwiftUI-WorkoutApp/Libraries/SWModels/Tests/SWModelsTest/ParkFormTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ private extension ParkFormTests {
139139
latitude: latitude,
140140
longitude: longitude,
141141
name: "Название площадки",
142-
photosOptional: [.init(id: 1)],
142+
photosOptional: [.init(id: 1, stringURL: "demo")],
143143
preview: nil,
144144
usersTrainHereCount: 1,
145145
commentsOptional: nil,

SwiftUI-WorkoutApp/Libraries/SWNetwork/Sources/SWNetwork/APIError.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ public enum APIError: Error, LocalizedError, Equatable {
1010
case serverError
1111
case invalidUserID
1212
case customError(code: Int, message: String)
13+
case decodingError
14+
case notConnectedToInternet
1315

1416
init(_ error: ErrorResponse, _ code: Int?) {
1517
if code == 401 {
@@ -55,6 +57,10 @@ public enum APIError: Error, LocalizedError, Equatable {
5557
"Некорректный идентификатор пользователя"
5658
case let .customError(code, error):
5759
"\(code), \(error)"
60+
case .decodingError:
61+
"Не удалось декодировать ответ"
62+
case .notConnectedToInternet:
63+
"Нет соединения с сетью"
5864
}
5965
}
6066
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public struct HTTPHeaderField: Equatable {
2+
let key: String
3+
let value: String
4+
5+
public init(key: String, value: String) {
6+
self.key = key
7+
self.value = value
8+
}
9+
10+
public static func authorizationBasic(_ token: String) -> HTTPHeaderField {
11+
.init(key: "Authorization", value: "Basic \(token)")
12+
}
13+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
public enum HTTPMethod: String, Equatable {
2+
case get = "GET"
3+
case post = "POST"
4+
case put = "PUT"
5+
case delete = "DELETE"
6+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import Foundation
2+
3+
public struct RequestComponents {
4+
let path: String
5+
let queryItems: [URLQueryItem]
6+
let httpMethod: HTTPMethod
7+
public var headerFields: [HTTPHeaderField]
8+
let body: Data?
9+
/// Токен для авторизации
10+
public var token: String?
11+
12+
/// Инициализатор
13+
/// - Parameters:
14+
/// - path: Путь запроса
15+
/// - queryItems: Параметры `query`, по умолчанию отсутствуют
16+
/// - httpMethod: Метод запроса
17+
/// - headerFields: Параметры хедеров, по умолчанию отсутствуют
18+
/// - body: Тело запроса, по умолчанию `nil`
19+
/// - token: Токен для авторизации, по умолчанию `nil`
20+
public init(
21+
path: String,
22+
queryItems: [URLQueryItem] = [],
23+
httpMethod: HTTPMethod,
24+
headerFields: [HTTPHeaderField] = [],
25+
body: Data? = nil,
26+
token: String? = nil
27+
) {
28+
self.path = path
29+
self.queryItems = queryItems
30+
self.httpMethod = httpMethod
31+
self.headerFields = headerFields
32+
self.body = body
33+
self.token = token
34+
}
35+
36+
var url: URL? {
37+
let scheme = "https"
38+
let host = "workout.su/api/v3"
39+
let stringComponents = "\(scheme)://\(host)\(path)"
40+
var components = URLComponents(string: stringComponents)
41+
if !queryItems.isEmpty {
42+
components?.queryItems = queryItems
43+
}
44+
return components?.url
45+
}
46+
}
47+
48+
extension RequestComponents {
49+
var urlRequest: URLRequest? {
50+
guard let url else { return nil }
51+
var request = URLRequest(url: url)
52+
request.httpMethod = httpMethod.rawValue
53+
request.httpBody = body
54+
var allHeaders = headerFields
55+
if let token {
56+
allHeaders.append(.authorizationBasic(token))
57+
}
58+
request.allHTTPHeaderFields = Dictionary(uniqueKeysWithValues: allHeaders.map { ($0.key, $0.value) })
59+
return request
60+
}
61+
}

0 commit comments

Comments
 (0)