Skip to content

Commit

Permalink
=htc Preserve the order of repeated parameters when retrieving query …
Browse files Browse the repository at this point in the history
…string as a multimap (#1270)

See playframework/playframework#7567
  • Loading branch information
marcospereira authored and jrudolph committed Jul 25, 2017
1 parent c58ca5e commit f0e52e6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
18 changes: 17 additions & 1 deletion akka-http-core/src/main/scala/akka/http/scaladsl/model/Uri.scala
Expand Up @@ -574,9 +574,25 @@ object Uri {
if (q.isEmpty) map else append(map.updated(q.key, q.value), q.tail)
append(Map.empty, this)
}

/**
* Returns this query as a map where keys can have multiple values. The parameter order is
* preserved, so that the following query:
*
* {{{
* a=1&a=2&a=3&a=4&b=1
* }}}
*
* Will return a map like:
*
* {{{
* "a" -> List(1, 2, 3, 4),
* "b" -> List(1)
* }}}
*/
def toMultiMap: Map[String, List[String]] = {
@tailrec def append(map: Map[String, List[String]], q: Query): Map[String, List[String]] =
if (q.isEmpty) map else append(map.updated(q.key, q.value :: map.getOrElse(q.key, Nil)), q.tail)
if (q.isEmpty) map else append(map.updated(q.key, map.getOrElse(q.key, Nil) :+ q.value), q.tail)
append(Map.empty, this)
}
override def newBuilder: mutable.Builder[(String, String), Query] = Query.newBuilder
Expand Down
Expand Up @@ -405,10 +405,14 @@ class UriSpec extends WordSpec with Matchers {
query.getAll("b") shouldEqual List("", "4", "2")
query.getAll("d") shouldEqual Nil
query.toMap shouldEqual Map("a" "1", "b" "", "c" "3")
query.toMultiMap shouldEqual Map("a" List("1"), "b" List("", "4", "2"), "c" List("3"))
query.toMultiMap shouldEqual Map("a" List("1"), "b" List("2", "4", ""), "c" List("3"))
query.toList shouldEqual List("a" "1", "b" "2", "c" "3", "b" "4", "b" "")
query.toSeq shouldEqual Seq("a" "1", "b" "2", "c" "3", "b" "4", "b" "")
}
"preserve the order of repeated parameters when retrieving as a multimap" in {
val query = Query("a=1&b=1&b=2&b=3&b=4&c=1")
query.toMultiMap shouldEqual Map("a" List("1"), "b" List("1", "2", "3", "4"), "c" List("1"))
}
"support conversion from list of name/value pairs" in {
import Query._
val pairs = List("key1" "value1", "key2" "value2", "key3" "value3")
Expand Down

0 comments on commit f0e52e6

Please sign in to comment.