@@ -9,6 +9,12 @@ import Foundation
99
1010extension URLRequest : Builder { }
1111
12+ extension CharacterSet {
13+
14+ static var uriAllowed = CharacterSet . urlQueryAllowed. subtracting ( . init( charactersIn: " + " ) )
15+
16+ }
17+
1218extension URLRequest {
1319
1420 subscript( header key: HTTPHeaderKey ) -> String ? {
@@ -28,41 +34,35 @@ extension URLRequest {
2834 var urlComponents = URLComponents ( )
2935 urlComponents. scheme = " https "
3036 urlComponents. path = path. fullPath
37+
38+ if let urlParameters = requestOptions? . urlParameters {
39+ urlComponents. queryItems = urlParameters. map { ( key, value) in . init( name: key. rawValue, value: value) }
40+ }
3141
3242 var request = URLRequest ( url: urlComponents. url!)
3343
3444 request. httpMethod = method. rawValue
3545 request. httpBody = body
36-
46+
3747 if let requestOptions = requestOptions {
38- request. setRequestOptions ( requestOptions)
48+
49+ requestOptions. headers. forEach { header in
50+ let ( value, field) = ( header. value, header. key. rawValue)
51+ request. setValue ( value, forHTTPHeaderField: field)
52+ }
53+
54+ // If body is set in query parameters, it will override the body passed as parameter to this function
55+ if let body = requestOptions. body, !body. isEmpty {
56+ let jsonEncodedBody = try ? JSONSerialization . data ( withJSONObject: body, options: [ ] )
57+ request. httpBody = jsonEncodedBody
58+ }
59+
3960 }
40-
61+
62+ request. httpBody = body
4163 self = request
4264 }
4365
44- mutating func setRequestOptions( _ requestOptions: RequestOptions ) {
45-
46- // Append headers
47- requestOptions. headers. forEach { setValue ( $0. value, forHTTPHeaderField: $0. key. rawValue) }
48-
49- // Append query items
50- if let url = url, var currentComponents = URLComponents ( string: url. absoluteString) {
51- let requestOptionsItems = requestOptions. urlParameters. map { URLQueryItem ( name: $0. key. rawValue, value: $0. value) }
52- var existingItems = currentComponents. queryItems ?? [ ]
53- existingItems. append ( contentsOf: requestOptionsItems)
54- currentComponents. queryItems = existingItems
55- self . url = currentComponents. url
56- }
57-
58- // Set body
59- if
60- let body = requestOptions. body,
61- let jsonData = try ? JSONSerialization . data ( withJSONObject: body, options: [ ] ) {
62- httpBody = jsonData
63- }
64- }
65-
6666}
6767
6868extension URLRequest {
0 commit comments