From 24b98636993f3dc891885aac648e004099716076 Mon Sep 17 00:00:00 2001 From: SomewhatDamaged Date: Mon, 6 Jan 2020 12:09:45 +1100 Subject: [PATCH] Featured image API route (#18) * Add route `/api/v1/json/features` Shows current featured image * Add route `/api/v1/json/features` Shows current featured image. * Removed binding * Moving this file to a more appropriate name. * Correctly named and placed Correctly named and placed to match its module name * Updated per review * Changed as per review Renamed to `PhilomenaWeb.Api.Json.FeaturedController` Moved to `lib/philomena_web/controllers/api/json/featured_controller.ex` * Updated route Route `/api/v1/json/images/featured` now uses `PhilomenaWeb.Api.Json.FeaturedController` * like this Co-authored-by: liamwhite --- .../api/json/image/featured_controller.ex | 29 +++++++++++++++++++ lib/philomena_web/router.ex | 3 ++ 2 files changed, 32 insertions(+) create mode 100644 lib/philomena_web/controllers/api/json/image/featured_controller.ex diff --git a/lib/philomena_web/controllers/api/json/image/featured_controller.ex b/lib/philomena_web/controllers/api/json/image/featured_controller.ex new file mode 100644 index 00000000..498d9c13 --- /dev/null +++ b/lib/philomena_web/controllers/api/json/image/featured_controller.ex @@ -0,0 +1,29 @@ +defmodule PhilomenaWeb.Api.Json.Image.FeaturedController do + use PhilomenaWeb, :controller + + alias PhilomenaWeb.ImageJson + alias Philomena.ImageFeatures.ImageFeature + alias Philomena.Images.Image + alias Philomena.Repo + import Ecto.Query + + def show(conn, _params) do + featured_image = + Image + |> join(:inner, [i], f in ImageFeature, on: [image_id: i.id]) + |> order_by([_i, f], desc: f.created_at) + |> limit(1) + |> preload([:tags, :user, :intensity]) + |> Repo.one() + + case featured_image do + nil -> + conn + |> put_status(:not_found) + |> text("") + + _ -> + json(conn, %{image: ImageJson.as_json(conn, featured_image)}) + end + end +end diff --git a/lib/philomena_web/router.ex b/lib/philomena_web/router.ex index dbc8414a..f94afb3a 100644 --- a/lib/philomena_web/router.ex +++ b/lib/philomena_web/router.ex @@ -95,6 +95,9 @@ defmodule PhilomenaWeb.Router do scope "/api/v1/json", PhilomenaWeb.Api.Json, as: :api_json do pipe_through [:accepts_json, :api, :ensure_tor_authorized] + scope "/images", Image, as: :image do + resources "/featured", FeaturedController, only: [:show], singleton: true + end resources "/images", ImageController, only: [:show] scope "/search", Search, as: :search do