Skip to content
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

fix: Ensure plain text response is only used for strings #29

Merged
merged 1 commit into from
May 21, 2024
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
2 changes: 1 addition & 1 deletion lib/apia/definitions/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def http_status_code
# API.
#
# @param errors [Apia::ManifestErrors]
# @reeturn [void]
# @return [void]
def validate(errors)
unless code.is_a?(Symbol)
errors.add self, 'InvalidCode', 'Code must be a symbol'
Expand Down
11 changes: 7 additions & 4 deletions lib/apia/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,14 @@ def body
#
# @return [Array]
def rack_triplet
case @type
when JSON
Rack.json_triplet(body, headers: headers, status: status)
when PLAIN
# Errors will always be sent as a hash intended for JSON encoding,
# even if the endpoint specifies a plain text response, so only
# send a pain response if the type is plaintext _and_ the body is
# a string
if @type == PLAIN && body.is_a?(String)
Rack.plain_triplet(body, headers: headers, status: status)
else
Rack.json_triplet(body, headers: headers, status: status)
end
end

Expand Down
8 changes: 8 additions & 0 deletions spec/specs/apia/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,14 @@
expect(response.rack_triplet[2][0]).to eq 'hello world'
expect(response.rack_triplet[1]['content-length']).to eq '11'
end

it 'should return JSON if the body is not a string' do
response = Apia::Response.new(request, endpoint)
response.body = { hello: 'world' }
expect(response.rack_triplet[1]['content-type']).to eq 'application/json'
expect(response.rack_triplet[1]['content-length']).to eq '17'
expect(response.rack_triplet[2][0]).to eq '{"hello":"world"}'
end
end

context 'with a legacy plain text response' do
Expand Down
Loading