From 1a44260211ec0a392b54be41b28dacc294a47ff8 Mon Sep 17 00:00:00 2001 From: "Liam P. White" Date: Wed, 28 Aug 2019 21:33:58 -0400 Subject: [PATCH] add primitive search controller --- .../controllers/search_controller.ex | 31 +++++++++++++++++++ lib/philomena_web/router.ex | 1 + 2 files changed, 32 insertions(+) create mode 100644 lib/philomena_web/controllers/search_controller.ex diff --git a/lib/philomena_web/controllers/search_controller.ex b/lib/philomena_web/controllers/search_controller.ex new file mode 100644 index 00000000..1fac9c5c --- /dev/null +++ b/lib/philomena_web/controllers/search_controller.ex @@ -0,0 +1,31 @@ +defmodule PhilomenaWeb.SearchController do + use PhilomenaWeb, :controller + + alias Philomena.Images.{Image, Query} + alias Pow.Plug + + import Ecto.Query + + plug ImageFilter + + def index(conn, params) do + filter = conn.assigns[:compiled_filter] + user = conn |> Plug.current_user() + + with {:ok, query} <- Query.compile(user, params["q"]) do + images = + Image.search_records( + %{ + query: %{bool: %{must: query, must_not: filter}}, + sort: %{created_at: :desc} + }, + Image |> preload(:tags) + ) + + render(conn, PhilomenaWeb.ImageView, "index.html", images: images, search_query: params["q"]) + else + {:error, msg} -> + render(conn, PhilomenaWeb.ImageView, "index.html", images: [], error: msg, search_query: params["q"]) + end + end +end diff --git a/lib/philomena_web/router.ex b/lib/philomena_web/router.ex index 831f04e4..ced5e8a1 100644 --- a/lib/philomena_web/router.ex +++ b/lib/philomena_web/router.ex @@ -27,6 +27,7 @@ defmodule PhilomenaWeb.Router do resources "/images", ImageController, only: [:index, :show] resources "/tags", TagController, only: [:index, :show] + resources "/search", SearchController, only: [:index] get "/:id", ImageController, :show end