api: add /random/media

This commit is contained in:
Lucas 2023-03-05 17:23:13 +00:00
parent 0c4ab53586
commit 04580aca72
2 changed files with 19 additions and 5 deletions

View File

@ -28,6 +28,7 @@ sub startup ($self)
$r->get("/media")->to("media#list");
$r->get("/media/:media_id")->to("media#show");
$r->get("/random/media")->to("random#media");
$r->get("/random/tag")->to("random#tag");
}

View File

@ -5,17 +5,30 @@ use warnings;
use Mojo::Base "Mojolicious::Controller";
sub media ($self)
{
$self->_random_entry("Media", sub ($c, $m) {
$c->redirect_to("/media/" . $m->media_id)
})
}
sub tag ($self)
{
my $tag = $self->schema->resultset("Tag")
->search({}, { order_by => \"random()", limit => 1 })->single;
$self->_random_entry("Tag", sub ($c, $t) {
$c->redirect_to("/tag/" . $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(
json => {error => "Tag not found"},
json => {error => "$rs not found"},
status => 404,
) if !defined($tag);
) if !defined($entry);
return $self->redirect_to("/tag/" . $tag->name);
return &$cb($self, $entry);
}
1;