Enable aggressive caching for the images endpoint

This commit is contained in:
Claudio Ortolina
2024-09-16 14:54:13 +01:00
parent cb8b42aad6
commit 1200215321
@@ -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