parse request body for array

This commit is contained in:
Aşkın Gedik 2015-11-10 13:30:16 +02:00
parent d280dd7f87
commit 51708ce8e7
2 changed files with 37 additions and 3 deletions

View file

@ -45,6 +45,34 @@ describe "ParamParser" do
params.should eq({"name": "Serdar"})
end
it "parses request body for array" do
route = Route.new "POST", "/" { }
request = HTTP::Request.new(
"POST",
"/",
body: "[1]",
headers: HTTP::Headers{"Content-Type": "application/json"},
)
params = Kemal::ParamParser.new(route, request).parse
params.should eq({"_json": [1]})
end
it "parses request body and query params" do
route = Route.new "POST", "/" { }
request = HTTP::Request.new(
"POST",
"/?foo=bar",
body: "[1]",
headers: HTTP::Headers{"Content-Type": "application/json"},
)
params = Kemal::ParamParser.new(route, request).parse
params.should eq({"foo": "bar", "_json": [1]})
end
it "handles no request body" do
route = Route.new "GET", "/" { }

View file

@ -39,10 +39,16 @@ class Kemal::ParamParser
def parse_json
return unless @request.body && @request.headers["Content-Type"]? == APPLICATION_JSON
body = @request.body as String
json = JSON.parse(body) as Hash
json.each do |k, v|
@params[k as String] = v as AllParamTypes
case json = JSON.parse(body)
when Hash
json.each do |k, v|
@params[k as String] = v as AllParamTypes
end
when Array
@params["_json"] = json
end
end