From 120021532190942d8fdc2343d5fc7ec6facc3b6b Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Mon, 16 Sep 2024 14:54:13 +0100 Subject: [PATCH] Enable aggressive caching for the images endpoint --- .../controllers/image_controller.ex | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/lib/music_library_web/controllers/image_controller.ex b/lib/music_library_web/controllers/image_controller.ex index f9c84dc2..74ad1370 100644 --- a/lib/music_library_web/controllers/image_controller.ex +++ b/lib/music_library_web/controllers/image_controller.ex @@ -3,17 +3,27 @@ defmodule MusicLibraryWeb.ImageController do alias MusicLibrary.Records - def show(conn, %{"record_id" => record_id}) do - # TODO: better error handling - # TODO: serve correct caching headers - image_data = Records.get_image!(record_id) + @one_year 31_536_000 - if image_data do - conn - |> put_resp_content_type("image/jpeg", "utf-8") - |> send_resp(200, image_data) - else - conn |> send_resp(404, "Not found") + def show(conn, %{"record_id" => record_id}) do + case Records.get_image!(record_id) do + nil -> + send_resp(conn, 404, "Not found") + + image_data -> + # TODO: move hash result to database + etag = :crypto.hash(:sha256, image_data) |> Base.encode16() + + case get_req_header(conn, "if-none-match") do + [^etag] -> + send_resp(conn, 304, "") + + _ -> + conn + |> put_resp_content_type("image/jpeg", "utf-8") + |> put_resp_header("cache-control", "public, max-age=#{@one_year}") + |> send_resp(200, image_data) + end end end end