Skip to content

Commit

Permalink
fix: ensure non-hash JSON bodies are converted to empty hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
adamcooke committed Mar 29, 2022
1 parent 7ecb025 commit 1c7efcd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/apia/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ def params
def parse_json_from_string(body)
return {} if body.empty?

JSON.parse(body)
response = JSON.parse(body)
response = {} unless response.is_a?(Hash)
response
rescue JSON::ParserError => e
raise InvalidJSONError, e.message
end
Expand Down
24 changes: 24 additions & 0 deletions spec/specs/apia/request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,29 @@
expect(request.json_body).to be_a Hash
expect(request.json_body['name']).to eq 'Jamie'
end

it 'returns an empty hash if the input is an array' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/json; charset=utf8', :input => '[]'))
expect(request.json_body).to be_a Hash
expect(request.json_body).to be_empty
end

it 'returns an empty hash if the input is an integer' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/json; charset=utf8', :input => '1234'))
expect(request.json_body).to be_a Hash
expect(request.json_body).to be_empty
end

it 'returns an empty hash if the input is a decimal' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/json; charset=utf8', :input => '12.34'))
expect(request.json_body).to be_a Hash
expect(request.json_body).to be_empty
end

it 'returns an empty hash if the input is a string' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/json; charset=utf8', :input => '"string"'))
expect(request.json_body).to be_a Hash
expect(request.json_body).to be_empty
end
end
end

0 comments on commit 1c7efcd

Please sign in to comment.