Skip to content
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
9 changes: 1 addition & 8 deletions lib/openapi_first/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,6 @@ def operation_id
@operation['operationId']
end

MULTIPART_CONTENT_TYPE = %r{\Amultipart/form-data\b}i
private_constant :MULTIPART_CONTENT_TYPE

private

def parse_request(request, route_params:)
Expand All @@ -82,11 +79,7 @@ def parse_query(query_string)
end

def build_body_parser(content_type, encoding)
if content_type.match?(MULTIPART_CONTENT_TYPE)
RequestBodyParsers['multipart/form-data'].new(encoding: encoding || {})
else
RequestBodyParsers[content_type]
end
RequestBodyParsers[content_type, { encoding: encoding || {} }]
end
end
end
17 changes: 8 additions & 9 deletions lib/openapi_first/request_body_parsers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ def register(pattern, parser)
parsers[pattern] = parser
end

def [](content_type)
def [](content_type, options = {})
key = parsers.keys.find { content_type.match?(_1) }
parsers.fetch(key) { DEFAULT }
parser = parsers.fetch(key) { DEFAULT }
return parser if parser.respond_to?(:call)

parser.new(options)
end
end

Expand Down Expand Up @@ -44,12 +47,8 @@ def self.read_body(request)
# `contentType: application/json` (or any */json), the field's raw value
# is JSON-parsed before schema validation.
class MultipartBodyParser
def initialize(encoding: {})
@encoding = encoding || {}
end

def self.call(request)
new.call(request)
def initialize(options)
@encoding = options[:encoding] || {}
end

def call(request)
Expand Down Expand Up @@ -89,7 +88,7 @@ def unpack_value(value)
end
end

register('multipart/form-data', MultipartBodyParser)
register(%r{\Amultipart/form-data\b}i, MultipartBodyParser)

register('application/x-www-form-urlencoded', lambda(&:POST))
end
Expand Down
5 changes: 2 additions & 3 deletions spec/request_body_parsers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,8 @@ def app = ->(_env) { Rack::Response.new.finish }

context 'with an encoding map' do
subject(:parser) do
OpenapiFirst::RequestBodyParsers::MultipartBodyParser.new(
encoding: { 'data' => { 'contentType' => 'application/json' } }
)
options = { encoding: { 'data' => { 'contentType' => 'application/json' } } }
described_class['multipart/form-data', options]
end

it 'parses fields whose encoding contentType is JSON' do
Expand Down
Loading