Skip to content

Instantly share code, notes, and snippets.

@ksmandersen
Created January 24, 2018 09:41
Show Gist options
  • Save ksmandersen/56cd54dc50e23b1dc7cc626cab119ca6 to your computer and use it in GitHub Desktop.
Save ksmandersen/56cd54dc50e23b1dc7cc626cab119ca6 to your computer and use it in GitHub Desktop.
Appending query parameters to URI's in Vapor
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
}
}
@homburg
Copy link

homburg commented Jan 24, 2018

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/#ParseQuery

Also you should probably encode keys and values, ie. https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment