Skip to content

Commit

Permalink
Merge pull request #16 from HUK-COBURG/issue/percent-encoded-query
Browse files Browse the repository at this point in the history
Fixed issue where percent escaped queries caused problems.
  • Loading branch information
JBoseckerHUK authored Sep 6, 2023
2 parents 657fa5a + 45cbe86 commit c4befc8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
15 changes: 9 additions & 6 deletions Sources/SchwiftyResources/Network/HttpResource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,9 @@ public extension HttpResource {
return nil
}

// MARK: - Private functions
// MARK: - Internal functions

private func buildUrlRequest() async throws -> URLRequest {
internal func buildUrlRequest() async throws -> URLRequest {
let url = try await buildUrl()

var urlRequest = URLRequest(url: url)
Expand All @@ -160,7 +160,7 @@ public extension HttpResource {
return urlRequest
}

private func buildUrl() async throws -> URL {
internal func buildUrl() async throws -> URL {
let url = try await self.url

guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
Expand All @@ -176,12 +176,15 @@ public extension HttpResource {
return URLQueryItem(name: key, value: value)
}

var newQueryItems: [URLQueryItem] = urlComponents.queryItems ?? []
newQueryItems.append(contentsOf: queryItems ?? [])
var newQueryItems = urlComponents.percentEncodedQueryItems ?? []

urlComponents.queryItems = queryItems

newQueryItems.append(contentsOf: urlComponents.percentEncodedQueryItems ?? [])
newQueryItems.sort { lhs, rhs in
return lhs.name < rhs.name
}
urlComponents.queryItems = newQueryItems.count > 0 ? newQueryItems : nil
urlComponents.percentEncodedQueryItems = newQueryItems.count > 0 ? newQueryItems : nil

guard let composedUrl = urlComponents.url else {
throw SchwiftyResourcesError.urlBroken
Expand Down
15 changes: 15 additions & 0 deletions Tests/SchwiftyResourcesTests/SchwiftyResourcesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,19 @@ final class SchwiftyResourcesTests: XCTestCase {

XCTAssertEqual(ricksToWrite, readRicks)
}

func testUrlBuilding() async throws {
struct UrlSampleResource: HttpResource {
typealias RequestBodyResourceEncoder = EmptyResourceCoder
typealias ResponseBodyResourceDecoder = EmptyResourceCoder

let requestQuery: [String : String]? = ["summer": "&"]
let url: URL = URL(string: "https://www.citadel.org?morty=%2F&rick=c-137")!
}

let resource = UrlSampleResource()
let builtUrl = try await resource.buildUrl()

XCTAssertEqual(builtUrl, URL(string: "https://www.citadel.org?morty=%2F&rick=c-137&summer=%26")!)
}
}

0 comments on commit c4befc8

Please sign in to comment.