From a0d3601c57b2784c5b8835b05490afc27eda3526 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sun, 19 Feb 2023 15:50:06 +0000 Subject: [PATCH] backend: refactor communication with api --- lib/PoorBooru.pm | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/PoorBooru.pm b/lib/PoorBooru.pm index 9188815..8314860 100644 --- a/lib/PoorBooru.pm +++ b/lib/PoorBooru.pm @@ -6,9 +6,11 @@ our $VERSION = v0.0.1; my $POORBOORU_API = setting("poorbooru_api"); -sub http_tiny () +sub api_request ($$;%) { - return HTTP::Tiny->new( + my ($method, $path, $params_hashref) = @_; + + my $http = HTTP::Tiny->new( timeout => 15, verify_SSL => true, agent => setting("appname") . " backend " . @@ -19,8 +21,14 @@ sub http_tiny () "Content-Type" => "application/json", }, ); + my $params = $http->www_form_urlencode($params_hashref // {}); + + return $http->request($method, "$POORBOORU_API$path" . + ($params ne "" ? "?$params" : "")); } +sub api_get ($;%) { api_request("GET", shift, @_) } + sub nav_pager ($$) { my ($p, $uri) = @_; @@ -54,7 +62,7 @@ get "/" => sub { my $page = query_parameters->get("page") // 1; send_error("Invalid page number", 400) if $page !~ /^[1-9][0-9]*$/; - my $res = http_tiny()->get("$POORBOORU_API/media?page=$page"); + my $res = api_get("/media", { page => $page }); send_error("API error", 500) if !$res->{success}; my $data = decode_json($res->{content}); @@ -75,9 +83,7 @@ get "/tags" => sub { my $page = query_parameters->get("page") // 1; send_error("Invalid page number", 400) if $page !~ /^[1-9][0-9]*$/; - my $http = http_tiny(); - my $params = $http->www_form_urlencode({ page => $page }); - my $res = $http->get("$POORBOORU_API/tags?$params"); + my $res = api_get("/tags", { page => $page }); send_error("API error", 500) if !$res->{success}; my $data = decode_json($res->{content}); @@ -97,7 +103,7 @@ get "/tags" => sub { get "/tag/:tag_id_or_name" => sub { my $tag_id_or_name = route_parameters->get("tag_id_or_name"); - my $res = http_tiny()->get("$POORBOORU_API/tag/$tag_id_or_name"); + my $res = api_get("/tag/$tag_id_or_name"); send_error("API error", 500) if !$res->{success}; my $data = decode_json($res->{content});