api: implement /media endpoint

Returns a paged collection of all media entries. Will be used for the
main page in a follow-up commit.
This commit is contained in:
Lucas 2023-02-18 17:06:00 +00:00
parent deb082f46c
commit 0876464b5b

View File

@ -5,7 +5,6 @@ use Dancer2::Plugin::DBIC;
our $VERSION = v0;
set serializer => "JSON";
set database => "db/booru.db";
use constant {
ROUTES => [
@ -19,8 +18,15 @@ use constant {
],
DEFAULT_CONTENT_TYPE => "application/json",
ROWS_PER_PAGE => 20,
};
sub surrounding_pages ($)
{
my $pager = $_[0]->pager;
return $pager->previous_page, $pager->next_page;
}
get "/meta" => sub {
return ROUTES;
};
@ -77,6 +83,24 @@ get "/tag/:tag_id_or_name" => sub {
};
};
get "/media" => sub {
my $page = query_parameters->get("page") // 1;
send_error("Invalide page number", 400) if $page !~ /^[1-9][0-9]*$/;
my $paged_media = schema("default")->resultset("Media")
->search({}, { order_by => "upload_date", rows => ROWS_PER_PAGE })
->page($page);
my ($prev, $next) = surrounding_pages($paged_media);
my @media = map { "/media/" . $_->media_id } $paged_media->all;
return {
next => ($next and "/media?page=$next"),
prev => ($prev and "/media?page=$prev"),
media => \@media,
};
};
get "/media/:media_id" => sub {
my $media = schema("default")->resultset("Media")
->single({ media_id => route_parameters->get("media_id") });