Skip to content

Commit

Permalink
Fix array coercion for array parameters with a $ref schema (#274)
Browse files Browse the repository at this point in the history
* Fix array coercion for array parameters with a $ref schema

Fixes jhthorsen/mojolicious-plugin-openapi#251

* perltidy
  • Loading branch information
simon816 authored Sep 12, 2024
1 parent f463896 commit 6677979
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
6 changes: 4 additions & 2 deletions lib/JSON/Validator/Schema/OpenAPIv2.pm
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,10 @@ sub _bundle_ref_path_expand {
sub _coerce_arrays {
my ($self, $val, $param) = @_;
my $data_type = data_type $val->{value};
my $schema_type = schema_type $param->{schema} || $param; # $param->{schema} is for OpenAPIv3
my $data_type = data_type $val->{value};
my $schema = $param->{schema} || $param; # $param->{schema} is for OpenAPIv3
$schema = $self->get($schema->{'$ref'} =~ s!^#!!r) if $schema->{'$ref'};
my $schema_type = schema_type $schema;
return $val->{value} = [$val->{value}] if $schema_type eq 'array' and $data_type ne 'array';
return $val->{value} = @{$val->{value}} ? $val->{value}[-1] : undef
if $schema_type ne 'array' and $data_type eq 'array';
Expand Down
27 changes: 25 additions & 2 deletions t/openapiv3-coerce-array.t
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use JSON::Validator;
use Test::More;

my $schema = JSON::Validator->new->schema('data://main/openapi.yaml')->schema;
my ($body, @errors);
my ($body, $query, @errors);

subtest 'number to array' => sub {
$body = {exists => 1, value => {id => 42}};
Expand All @@ -23,9 +23,16 @@ subtest 'already an array' => sub {
is "@errors", "", "valid";
};

subtest 'parameter array schema is $ref' => sub {
$query = {exists => 1, value => [42, 43]};
@errors = $schema->validate_request([get => '/test'], {query => \&query});
is "@errors", "", "valid";
};

done_testing;

sub body {$body}
sub body {$body}
sub query {$query}

__DATA__
@@ openapi.yaml
Expand Down Expand Up @@ -53,3 +60,19 @@ paths:
responses:
200:
description: OK
get:
parameters:
- name: id
in: query
required: true
schema:
$ref: '#/components/schemas/IntArray'
responses:
200:
description: OK
components:
schemas:
IntArray:
type: array
items:
type: integer

0 comments on commit 6677979

Please sign in to comment.