Unexpected behaviour when the request body is an array

18 views
Skip to first unread message

Artur Trapp

unread,
Oct 22, 2021, 9:25:26 AM10/22/21
to Roda
Hello 👋🏻 
Apologies if this is intended behavior or if I am just using the library wrongly. 

I have created a `POST` endpoint whose body is an array, like this:


[
        {
            "prop1": "1",
            "prop2": "2"
        },
        {
            "prop1": "a",
            "prop2": "b"
        }
]


when I tried to access the @_request.params, it threw me the following error: TypeError: no implicit conversion of Array into Hash. The stack trace led me to the line 469 of the rack/request.rb file, so I am not really sure if this is an issue with `rack` or `roda` though.

The code where the bug happens is as follows:

def params
    self.GET.merge(self.POST)
end

I presumed this happens because self.POST is an Array, and merge receives a Hash as an argument, so the exception is thrown.

I did a workaround, like this:

begin
    params = @_request.params
rescue StandardError
    params = @_request.POST
end

But I am not sure this is the right thing to do. Any clues here?

Jeremy Evans

unread,
Oct 22, 2021, 10:30:26 AM10/22/21
to ruby...@googlegroups.com
I assume you are using the json_parser plugin, or this wouldn't work at all, as the JSON request body wouldn't be parsed.  If so, you can use wrap: :always or wrap: :unless_hash option to the json_parser plugin.  That will allow you to access the JSON array from the request body using r.params['_json'].

Thanks,
Jeremy
Reply all
Reply to author
Forward
0 new messages