Skip to content

Commit 0ff0cc4

Browse files
authored
Merge pull request #480 from ahx/register-request-body-parser
Remove redundant matching of multipart content-type.
2 parents e3b36b7 + dd9eaf8 commit 0ff0cc4

3 files changed

Lines changed: 11 additions & 20 deletions

File tree

lib/openapi_first/request.rb

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,6 @@ def operation_id
5454
@operation['operationId']
5555
end
5656

57-
MULTIPART_CONTENT_TYPE = %r{\Amultipart/form-data\b}i
58-
private_constant :MULTIPART_CONTENT_TYPE
59-
6057
private
6158

6259
def parse_request(request, route_params:)
@@ -82,11 +79,7 @@ def parse_query(query_string)
8279
end
8380

8481
def build_body_parser(content_type, encoding)
85-
if content_type.match?(MULTIPART_CONTENT_TYPE)
86-
RequestBodyParsers['multipart/form-data'].new(encoding: encoding || {})
87-
else
88-
RequestBodyParsers[content_type]
89-
end
82+
RequestBodyParsers[content_type, { encoding: encoding || {} }]
9083
end
9184
end
9285
end

lib/openapi_first/request_body_parsers.rb

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@ def register(pattern, parser)
1414
parsers[pattern] = parser
1515
end
1616

17-
def [](content_type)
17+
def [](content_type, options = {})
1818
key = parsers.keys.find { content_type.match?(_1) }
19-
parsers.fetch(key) { DEFAULT }
19+
parser = parsers.fetch(key) { DEFAULT }
20+
return parser if parser.respond_to?(:call)
21+
22+
parser.new(options)
2023
end
2124
end
2225

@@ -44,12 +47,8 @@ def self.read_body(request)
4447
# `contentType: application/json` (or any */json), the field's raw value
4548
# is JSON-parsed before schema validation.
4649
class MultipartBodyParser
47-
def initialize(encoding: {})
48-
@encoding = encoding || {}
49-
end
50-
51-
def self.call(request)
52-
new.call(request)
50+
def initialize(options)
51+
@encoding = options[:encoding] || {}
5352
end
5453

5554
def call(request)
@@ -89,7 +88,7 @@ def unpack_value(value)
8988
end
9089
end
9190

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

9493
register('application/x-www-form-urlencoded', lambda(&:POST))
9594
end

spec/request_body_parsers_spec.rb

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,8 @@ def app = ->(_env) { Rack::Response.new.finish }
2929

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

3736
it 'parses fields whose encoding contentType is JSON' do

0 commit comments

Comments
 (0)