Skip to content

fix: JSON-encode array request bodies #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions lib/ruby_http_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def wait!
# - +response+ -> A NET::HTTP response object
#
attr_reader :status_code, :body, :headers

def initialize(response)
@status_code = response.code
@body = response.body
Expand Down Expand Up @@ -265,7 +266,7 @@ def _(name = nil)
# (e.g. client.name.name.get())
#
# * *Args* :
# - The args are autmoatically passed in
# - The args are automatically passed in
# * *Returns* :
# - Client object or Response object
#
Expand Down Expand Up @@ -296,8 +297,8 @@ def build_http_request(http_method)

def update_content_type(http_method)
if @request_body && content_type_json?
# If body is a hash, encode it; else leave it alone
@request.body = if @request_body.class == Hash
# If body is a hash or array, encode it; else leave it alone
@request.body = if [Hash, Array].include?(@request_body.class)
@request_body.to_json
else
@request_body
Expand Down
16 changes: 15 additions & 1 deletion test/test_ruby_http_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def test_build_request_post_multipart
assert_equal('hogebody', client.request.body)
end

def test_json_body_encode
def test_json_body_encode_hash
headers = {
'Content-Type' => 'application/json'
}
Expand All @@ -203,6 +203,20 @@ def test_json_body_encode
assert_equal('{"this_is":"json"}', response.request_body)
end

def test_json_body_encode_array
headers = {
'Content-Type' => 'application/json'
}
client = MockRequestWithRequestBody.new(
host: 'https://localhost',
request_headers: headers
)
name = 'post'
args = [{ 'request_body' => [{ 'this_is' => 'json' }] }]
response = client.build_request(name, args)
assert_equal('[{"this_is":"json"}]', response.request_body)
end

def test_json_body_do_not_reencode
headers = {
'Content-Type' => 'application/json'
Expand Down