api: only do random entry fetching in _random_entry

This commit is contained in:
Lucas 2023-03-25 13:58:24 +00:00
parent 48f3445706
commit 724bfbc82a

View File

@ -7,28 +7,31 @@ use Mojo::Base "Mojolicious::Controller";
sub media ($self) sub media ($self)
{ {
$self->_random_entry("Media", sub ($c, $m) { my $media = $self->_random_entry("Media");
$c->redirect_to("media_show", media_id => $m->media_id)
}) return $self->render(
json => {error => "Media not found"},
status => 404,
) if !defined($media);
return $self->redirect_to("media_show", media_id => $media->media_id);
} }
sub tag ($self) sub tag ($self)
{ {
$self->_random_entry("Tag", sub ($c, $t) { my $tag = $self->_random_entry("Tag");
$c->redirect_to("tag_show", tag_id_or_name => $t->name)
})
}
sub _random_entry ($self, $rs, $cb) {
my $entry = $self->schema->resultset($rs)
->search(undef, { order_by => \"random()", rows => 1 })->single;
return $self->render( return $self->render(
json => {error => "$rs not found"}, json => {error => "Tag not found"},
status => 404, status => 404,
) if !defined($entry); ) if !defined($tag);
return $self->redirect_to("tag_show", tag_id_or_name => $tag->name);
}
return $cb->($self, $entry); sub _random_entry ($self, $rs) {
$self->schema->resultset($rs)
->search(undef, { order_by => \"random()", rows => 1 })->single
} }
1; 1;