Created
January 24, 2018 09:41
-
-
Save ksmandersen/56cd54dc50e23b1dc7cc626cab119ca6 to your computer and use it in GitHub Desktop.
Appending query parameters to URI's in Vapor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension URI { | |
public func appendingQueryParameters(_ parameters: [String: String]) -> URI { | |
let allParameters = mergeParameters(queryParameters(fromQuery: query), rhs: parameters) | |
let newQuery = toQuery(parameters: allParameters) | |
return URI(scheme: scheme, userInfo: userInfo, hostname: hostname, port: port, path: path, | |
query: newQuery, fragment: fragment) | |
} | |
private func toQuery(parameters: [String: String]) -> String { | |
let joined = parameters.reduce("", { result, next in | |
return result + next.0 + "=" + next.1 + "&" | |
}) | |
return String(joined[joined.startIndex..<joined.index(before: joined.endIndex)]) | |
} | |
private func queryParameters(fromQuery query: String?) -> [String: String] { | |
var params = [String: String]() | |
guard let query = query else { return params } | |
let comps = query.components(separatedBy: "&").reversed() | |
comps.forEach { str in | |
let expr = str.components(separatedBy: "=") | |
params[expr[0]] = expr[1] | |
} | |
return params | |
} | |
private func mergeParameters(_ lhs: [String: String], rhs: [String: String]) -> [String: String] { | |
var res = lhs | |
for (k, v) in rhs { | |
res[k] = v | |
} | |
return res | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice 👍
Saw this on twitter :-)
How does vapor handle arrays in query strings? This varies a lot between languages/frameworks, ie. node/express: http://httpbin.org/get?something=1&something=2
I's totally legal to have the same query key multiple times, golang uses something like
[string: [string]]
for the parameter representation for this reason: https://golang.org/pkg/net/url/#ParseQueryAlso you should probably encode keys and values, ie. https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding