From 04580aca726f22e33848bff2cb242701df40914b Mon Sep 17 00:00:00 2001 From: Lucas Date: Sun, 5 Mar 2023 17:23:13 +0000 Subject: [PATCH] api: add /random/media --- lib/PoorBooru/API/V0.pm | 1 + lib/PoorBooru/API/V0/Controller/Random.pm | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/PoorBooru/API/V0.pm b/lib/PoorBooru/API/V0.pm index 69f22bd..31a156a 100644 --- a/lib/PoorBooru/API/V0.pm +++ b/lib/PoorBooru/API/V0.pm @@ -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"); } diff --git a/lib/PoorBooru/API/V0/Controller/Random.pm b/lib/PoorBooru/API/V0/Controller/Random.pm index 6ccfe8c..775ebaf 100644 --- a/lib/PoorBooru/API/V0/Controller/Random.pm +++ b/lib/PoorBooru/API/V0/Controller/Random.pm @@ -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;