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

Fixed JSON request had 1 or 0 array elements and add json_parameters method #21

Merged
merged 6 commits into from
Nov 9, 2023
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
29 changes: 29 additions & 0 deletions lib/Kossy.pm
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,35 @@ validate parameters using L<Kossy::Validator>

These methods are the accessor to raw values. 'raw' means the value is not decoded.

=item body_parameters

Accessor to decoded body parameters. It's Hash::MultiValue object.

=item query_parameters

Accessor to decoded query parameters. It's Hash::MultiValue object.

=item json_parameters

Accessor to decoded JSON body parameters. It's B<NOT> Hash::MultiValue object.
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the reason for using Hash::MultiValue is to handle Arrays.

If JSON can handle structures such as Arrays, so I prefer to not using Hash::MultiValue.


post '/api' => sub {
my ($self, $c) = @_;
my $foo = $c->req->json_parameters->{foo}; # bar
};

# requrest
# $ua->requrest(
# HTTP::Request->new(
# "POST",
# "http://example.com/api",
# [ "Content-Type" => 'application/json', "Content-Length" => 13 ],
# '{"foo":"bar"}'
# )
# );

NOTE: Not need to set C<kossy.request.parse_json_body> to 1
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When using json_parameters accessor, this setting is no longer necessary for simplicity.


=back

=head1 Kossy::Response
Expand Down
49 changes: 42 additions & 7 deletions lib/Kossy/Request.pm
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ $json_parser->register(
'HTTP::Entity::Parser::JSON'
);

my $json_only_parser = HTTP::Entity::Parser->new();
$json_only_parser->register(
'application/json',
'HTTP::Entity::Parser::JSON'
);

sub _build_request_body_parser {
my $self = shift;
if ( $self->env->{'kossy.request.parse_json_body'} ) {
Expand Down Expand Up @@ -117,11 +123,32 @@ sub uploads {
sub body_parameters {
my ($self) = @_;
$self->env->{'kossy.request.body'} ||= do {
my @body_parameters = $self->env->{'kossy.request.parse_json_body'}
? $self->body_parameters_raw->flatten
: @{$self->_body_parameters()};
Hash::MultiValue->new(map { _decode_recursively($_) } @{$self->_body_parameters()});
}
}

sub json_parameters {
my ($self) = @_;
$self->env->{'kossy.request.json_body'} ||= do {
+{ map { _decode_recursively($_) } @{$self->_json_parameters()} }
}
}

Hash::MultiValue->new(map { Encode::decode_utf8($_) } @body_parameters);
sub _decode_recursively {
my $v = shift;
if (my $r = ref $v) {
if ($r eq 'ARRAY') {
return [ map { _decode_recursively($_) } @$v ];
}
elsif ($r eq 'HASH') {
return { map { Encode::decode_utf8($_) => _decode_recursively($v->{$_}) } keys %$v };
}
else {
die 'Cannot decode ' . $v;
}
}
else {
return Encode::decode_utf8($v);
}
}

Expand All @@ -148,6 +175,16 @@ sub _body_parameters {
}
return $self->env->{'kossy.request.body_parameters'};
}

sub _json_parameters {
my $self = shift;
unless ($self->env->{'kossy.request.json_parameters'}) {
my ($params) = $json_only_parser->parse($self->env);
$self->env->{'kossy.request.json_parameters'} = $params;
}
return $self->env->{'kossy.request.json_parameters'};
}

sub _query_parameters {
my $self = shift;
unless ( $self->env->{'kossy.request.query_parameters'} ) {
Expand All @@ -160,9 +197,7 @@ sub _query_parameters {
sub body_parameters_raw {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change reverts back to the v0.60 code.

Kossy/lib/Kossy/Request.pm

Lines 155 to 161 in 4191730

sub body_parameters_raw {
my $self = shift;
unless ($self->env->{'plack.request.body'}) {
$self->env->{'plack.request.body'} = Hash::MultiValue->new(@{$self->_body_parameters});
}
return $self->env->{'plack.request.body'};
}

my $self = shift;
unless ($self->env->{'plack.request.body'}) {
$self->env->{'plack.request.body'} = $self->env->{'kossy.request.parse_json_body'}
? Hash::MultiValue->from_mixed(@{$self->_body_parameters})
: Hash::MultiValue->new(@{$self->_body_parameters});
$self->env->{'plack.request.body'} = Hash::MultiValue->new(@{$self->_body_parameters});
}
return $self->env->{'plack.request.body'};
}
Expand Down
159 changes: 144 additions & 15 deletions t/002_kossy-request/parameters.t
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use strict;
use warnings;
use utf8;

use Test::More;
use Kossy;
Expand Down Expand Up @@ -90,12 +91,20 @@ subtest 'When POST request with parameter values are multi' => sub {
};

subtest 'When POST request with parameter values are array' => sub {
my $request = POST "/?q=123&q=456", { b => [ "hello", "world" ] };
subtest 'If requested an empty array, then the body parameters is empty.' => sub {
my $request = POST "/?q=123", { b => [] };
run_test($request, { q => '123' }, {} );
};

run_test($request,
{ q => ['123', '456'] },
{ b => ['hello', 'world'] }
);
subtest 'If requested an one element array, then the body parameters is single value.' => sub {
my $request = POST "/?q=123", { b => ['hello'] };
run_test($request, { q => '123' }, { b => 'hello' } );
};

subtest 'If requested an multi elements array, then the body parameters is array.' => sub {
my $request = POST "/?q=123", { b => ['hello', 'world'] };
run_test($request, { q => '123' }, { b => ['hello', 'world'] } );
};
};

subtest 'When POST JSON request with parameter values are single' => sub {
Expand All @@ -112,18 +121,138 @@ subtest 'When POST JSON request with parameter values are single' => sub {
);
};

subtest 'When POST JSON request with parameter values are array' => sub {
my $request = POST "/?q=123&q=456";
subtest 'When POST JSON request with parameter value is complex structure' => sub {

my $encocded_json = encode_json({ b => ['hello', 'world'] });
$request->header('Content-Type' => 'application/json; charset=utf-8');
$request->header('Content-Length' => length $encocded_json);
$request->content($encocded_json);
my $run_test = sub {
my ($request_data) = @_;

run_test($request,
{ q => ['123', '456'] },
{ b => ['hello', 'world'] }
);
# body parameters are expected to match $request_data
my $expected = $request_data;

my $request = POST "/?q=123";

my $encocded_json = encode_json($request_data);
$request->header('Content-Type' => 'application/json; charset=utf-8');
$request->header('Content-Length' => length $encocded_json);
$request->content($encocded_json);

run_test($request, { q => '123' }, $expected);
};

subtest 'Empty array' => sub {
$run_test->({ b => [] });
};

subtest 'One element array' => sub {
$run_test->({ b => ['hello'] });
};

subtest 'Multi elements array' => sub {
$run_test->({ b => ['hello', 'world'] });
};

subtest 'Array with undef' => sub {
$run_test->({ b => ['hello', undef] });
};

subtest 'Empty hashref' => sub {
$run_test->({ b => { } });
};

subtest 'One element hashref' => sub {
$run_test->({ b => { 'foo' => 1 } });
};

subtest 'Multi elements hashref' => sub {
$run_test->({ b => { 'foo' => 1, 'bar' => 2 } });
};

subtest 'HashRef with undef' => sub {
$run_test->({ b => { 'hello' => undef } });
};

subtest 'Complex case' => sub {
$run_test->({
b1 => 'hello',
b2 => [ 'hono', '🔥' ],
b3 => { 'foo' => 1, 'bar' => 2, 'boo' => '👍' },
b4 => undef,
});
};
};

subtest 'Use json_parameters' => sub {

my $run_test = sub {
my $request_data = shift;

# JSON parameters are expected to match $request_data
my $expected = $request_data;

my $app = sub {
my $env = shift;
my $req = Kossy::Request->new($env);

is_deeply $req->json_parameters, $expected;

$req->new_response(200)->finalize;
};

# NOTE: json_parameters not need to set kossy.request.parse_json_body
test_psgi $app, sub {
my $cb = shift;

my $request = POST "/";

my $encocded_json = encode_json($request_data);
$request->header('Content-Type' => 'application/json; charset=utf-8');
$request->header('Content-Length' => length $encocded_json);
$request->content($encocded_json);

$cb->($request);
};
};

subtest 'Empty array' => sub {
$run_test->({ b => [] });
};

subtest 'One element array' => sub {
$run_test->({ b => ['hello'] });
};

subtest 'Multi elements array' => sub {
$run_test->({ b => ['hello', 'world'] });
};

subtest 'Array with undef' => sub {
$run_test->({ b => ['hello', undef] });
};

subtest 'Empty hashref' => sub {
$run_test->({ b => { } });
};

subtest 'One element hashref' => sub {
$run_test->({ b => { 'foo' => 1 } });
};

subtest 'Multi elements hashref' => sub {
$run_test->({ b => { 'foo' => 1, 'bar' => 2 } });
};

subtest 'HashRef with undef' => sub {
$run_test->({ b => { 'hello' => undef } });
};

subtest 'Complex case' => sub {
$run_test->({
b1 => 'hello',
b2 => [ 'hono', '🔥' ],
b3 => { 'foo' => 1, 'bar' => 2, 'boo' => '👍' },
b4 => undef,
});
};
};

done_testing;
Loading
Loading