1
0
Fork 0
mirror of https://github.com/edgurgel/httparrot synced 2025-04-05 08:12:31 -04:00

Support multiple values same key on /get

This commit is contained in:
Eduardo Gurgel 2014-05-18 16:11:10 +12:00
parent e087b786fb
commit 96a4d76e3c
2 changed files with 41 additions and 3 deletions

View file

@ -6,8 +6,29 @@ defmodule HTTParrot.GeneralRequestInfo do
{{ip, _port}, req} = :cowboy_req.peer(req)
ip = :inet_parse.ntoa(ip) |> to_string
if args == [], do: args = [{}]
args = flatten_dict(args)
{[args: args, headers: headers, url: url, origin: ip], req}
end
@doc """
Group by keys and if duplicated keys, aggregate them as a list
iex> flatten_dict([a: "v1", a: "v2", b: "v3"])
%{a: ["v1", "v2"], b: "v3"}
"""
@spec flatten_dict(list) :: map
def flatten_dict([]), do: %{}
def flatten_dict(args) do
Enum.group_by(args, %{}, fn {k, _} -> k end)
|> Enum.traverse(fn {k1, v1} ->
values = Enum.map(v1, fn {_, v2} -> v2 end)
|> Enum.reverse
|> flatten_if_list_of_one
{k1, values}
end)
end
defp flatten_if_list_of_one([h]), do: h
defp flatten_if_list_of_one(list), do: list
end

View file

@ -11,6 +11,8 @@ defmodule HTTParrot.GeneralRequestInfoTest do
unload :cowboy_req
end
doctest HTTParrot.GeneralRequestInfo
test "returns a list of args, headers, url and original ip" do
qs_vals = [{"a", "b"}]
headers = [header1: "value 1", header2: "value 2"]
@ -21,7 +23,22 @@ defmodule HTTParrot.GeneralRequestInfoTest do
expect(:cowboy_req, :url, 1, {url, :req4})
expect(:cowboy_req, :peer, 1, {{ip, :host}, :req5})
assert retrieve(:req1) == {[args: qs_vals, headers: headers, url: url, origin: "127.1.2.3"], :req5}
assert retrieve(:req1) == {[args: %{"a" => "b"}, headers: headers, url: url, origin: "127.1.2.3"], :req5}
assert validate :cowboy_req
end
test "returns a list of args with duplicated keys, headers, url and original ip" do
qs_vals = [{"a", "b"}, {"a", "c"}]
headers = [header1: "value 1", header2: "value 2"]
ip = {127, 1, 2, 3}
url = "http://localhost/get?a=b&a=c"
expect(:cowboy_req, :qs_vals, 1, {qs_vals, :req2})
expect(:cowboy_req, :headers, 1, {headers, :req3})
expect(:cowboy_req, :url, 1, {url, :req4})
expect(:cowboy_req, :peer, 1, {{ip, :host}, :req5})
assert retrieve(:req1) == {[args: %{"a" => ["b", "c"]}, headers: headers, url: url, origin: "127.1.2.3"], :req5}
assert validate :cowboy_req
end
@ -36,7 +53,7 @@ defmodule HTTParrot.GeneralRequestInfoTest do
expect(:cowboy_req, :url, 1, {url, :req4})
expect(:cowboy_req, :peer, 1, {{ip, :host}, :req5})
assert retrieve(:req1) == {[args: [{}], headers: headers, url: url, origin: "127.1.2.3"], :req5}
assert retrieve(:req1) == {[args: %{}, headers: headers, url: url, origin: "127.1.2.3"], :req5}
assert validate :cowboy_req
end