refactor: use respond_once helper in async handlers

This commit is contained in:
2025-12-29 15:31:59 +01:00
parent af5a924ae3
commit 7005e0852a

View File

@@ -6,30 +6,33 @@ use Urupam::Utils qw(sanitize_input get_error_status sanitize_error_message);
sub shorten {
my $c = shift;
$c->render_later;
my $responded = 0;
my $url_service = $c->url_service;
my $validator = $c->validator;
my $json = $c->req->json;
unless ( defined $json && ref $json eq 'HASH' ) {
return if $responded;
$responded = 1;
$c->respond_once(
sub {
$c->render(
json => { error => 'Invalid JSON format' },
status => 400
);
}
);
return;
}
my $original_url = sanitize_input( $json->{url} || '' );
unless ($original_url) {
return if $responded;
$responded = 1;
$c->respond_once(
sub {
$c->render(
json => { error => 'URL is required' },
status => 400
);
}
);
return;
}
@@ -43,8 +46,8 @@ sub shorten {
)->then(
sub {
my $short_code = shift;
return if $responded;
$responded = 1;
$c->respond_once(
sub {
my $short_url = $c->url_for("/$short_code")->to_abs;
$c->render(
json => {
@@ -55,12 +58,15 @@ sub shorten {
}
);
}
);
}
)->catch(
sub {
my $err = shift;
return if $responded;
$responded = 1;
$c->app->log->error("API URL validation/creation error: $err");
$c->respond_once(
sub {
$c->app->log->error(
"API URL validation/creation error: $err");
my $status = get_error_status($err);
my $sanitized_error = sanitize_error_message($err);
$c->render(
@@ -69,31 +75,34 @@ sub shorten {
);
}
);
}
);
}
sub get_url {
my $c = shift;
$c->render_later;
my $responded = 0;
my $short_code = $c->param('short_code') // '';
my $url_service = $c->url_service;
my $validator = $c->validator;
unless ( $short_code && $validator->validate_short_code($short_code) ) {
return if $responded;
$responded = 1;
$c->respond_once(
sub {
$c->render(
json => { error => 'Invalid short code format' },
status => 400
);
}
);
return;
}
return $url_service->get_original_url($short_code)->then(
sub {
my $original_url = shift;
return if $responded;
$responded = 1;
$c->respond_once(
sub {
if ($original_url) {
my $short_url = $c->url_for("/$short_code")->to_abs;
$c->render(
@@ -112,11 +121,13 @@ sub get_url {
);
}
}
);
}
)->catch(
sub {
my $err = shift;
return if $responded;
$responded = 1;
$c->respond_once(
sub {
$c->app->log->error("API URL retrieval error: $err");
my $status = get_error_status($err);
my $sanitized_error = sanitize_error_message($err);
@@ -126,6 +137,8 @@ sub get_url {
);
}
);
}
);
}
1;