From 51708ce8e720bd2ab19c23dc6da605e34262c793 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?A=C5=9Fk=C4=B1n=20Gedik?= Date: Tue, 10 Nov 2015 13:30:16 +0200 Subject: [PATCH] parse request body for array --- spec/param_parser_spec.cr | 28 ++++++++++++++++++++++++++++ src/kemal/param_parser.cr | 12 +++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/spec/param_parser_spec.cr b/spec/param_parser_spec.cr index 83ff016..e7c833f 100644 --- a/spec/param_parser_spec.cr +++ b/spec/param_parser_spec.cr @@ -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", "/" { } diff --git a/src/kemal/param_parser.cr b/src/kemal/param_parser.cr index f8d3124..a434a74 100644 --- a/src/kemal/param_parser.cr +++ b/src/kemal/param_parser.cr @@ -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