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

feat: Allow JSON requests with a vendor specific JSON content type #34

Merged
merged 1 commit into from
Feb 28, 2025
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
4 changes: 3 additions & 1 deletion lib/apia/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ def parse_json_from_string(body)
end

def get_json_body_from_body
return unless content_type =~ /\Aapplication\/json/
# Allow for either standard json content type (ie: application/json)
# or a vendor specific type with a json suffix (eg: application/vnd.docker.distribution.events.v2+json)
return unless content_type =~ /\Aapplication\/(|.*\+)json/
return unless body?

parse_json_from_string(body.read)
Expand Down
10 changes: 8 additions & 2 deletions spec/specs/apia/request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
end

context '#json_body' do
it 'should return nil if the content type is not application/json' do
request = Apia::Request.new(Rack::MockRequest.env_for('/'))
it 'should return nil if the content type is not json' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/vnd.docker.distribution.events.v2-json', :input => '{"name":"Lauren"}'))
expect(request.json_body).to be nil
end

Expand All @@ -23,6 +23,12 @@
expect(request.json_body['name']).to eq 'Lauren'
end

it 'should return a hash when valid JSON is provided with a vendor specific json content type' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/vnd.docker.distribution.events.v2+json', :input => '{"name":"Lauren"}'))
expect(request.json_body).to be_a Hash
expect(request.json_body['name']).to eq 'Lauren'
end

it 'should return an empty hash when the body is missing but the content type is provided' do
request = Apia::Request.new(Rack::MockRequest.env_for('/', 'CONTENT_TYPE' => 'application/json', :input => ''))
expect(request.json_body).to be_a Hash
Expand Down
Loading