Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure plus character in query parameter is percent encoded #17

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion Sources/Endpoints/Endpoint+URLRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ import Foundation
import FoundationNetworking
#endif

extension CharacterSet {
static let urlQueryAllowedWithoutPlus: CharacterSet = {
var characterSet = CharacterSet.urlQueryAllowed
characterSet.remove(charactersIn: "+")
return characterSet
}()
}

extension Endpoint {

/// Generates a `URLRequest` given the associated request value.
Expand Down Expand Up @@ -75,8 +83,19 @@ extension Endpoint {
return nil
}

// URLComponents does not encode "+" by default because it is included in `.urlQueryAllowed`. To ensure
// that it is encoded, we manually encode the query items using our custom character set, then assign the
// result to `percentEncodedQuery` to prevent URLComponents from re-encoding the values.
if !urlQueryItems.isEmpty {
components.queryItems = urlQueryItems
let queryString = urlQueryItems.compactMap { item -> String? in
guard
let value = item.value,
let encodedName = item.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowedWithoutPlus),
let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowedWithoutPlus)
else { return nil }
return "\(encodedName)=\(encodedValue)"
}.joined(separator: "&")
components.percentEncodedQuery = queryString
}

let baseUrl = environment.baseUrl
Expand Down
Loading