Skip to content

Commit dbf8a5e

Browse files
authored
fix: Ensure plain text response is only used for strings (#29)
1 parent aac227e commit dbf8a5e

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

lib/apia/definitions/error.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def http_status_code
3737
# API.
3838
#
3939
# @param errors [Apia::ManifestErrors]
40-
# @reeturn [void]
40+
# @return [void]
4141
def validate(errors)
4242
unless code.is_a?(Symbol)
4343
errors.add self, 'InvalidCode', 'Code must be a symbol'

lib/apia/response.rb

+7-4
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,14 @@ def body
7070
#
7171
# @return [Array]
7272
def rack_triplet
73-
case @type
74-
when JSON
75-
Rack.json_triplet(body, headers: headers, status: status)
76-
when PLAIN
73+
# Errors will always be sent as a hash intended for JSON encoding,
74+
# even if the endpoint specifies a plain text response, so only
75+
# send a pain response if the type is plaintext _and_ the body is
76+
# a string
77+
if @type == PLAIN && body.is_a?(String)
7778
Rack.plain_triplet(body, headers: headers, status: status)
79+
else
80+
Rack.json_triplet(body, headers: headers, status: status)
7881
end
7982
end
8083

spec/specs/apia/response_spec.rb

+8
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,14 @@
135135
expect(response.rack_triplet[2][0]).to eq 'hello world'
136136
expect(response.rack_triplet[1]['content-length']).to eq '11'
137137
end
138+
139+
it 'should return JSON if the body is not a string' do
140+
response = Apia::Response.new(request, endpoint)
141+
response.body = { hello: 'world' }
142+
expect(response.rack_triplet[1]['content-type']).to eq 'application/json'
143+
expect(response.rack_triplet[1]['content-length']).to eq '17'
144+
expect(response.rack_triplet[2][0]).to eq '{"hello":"world"}'
145+
end
138146
end
139147

140148
context 'with a legacy plain text response' do

0 commit comments

Comments
 (0)