Extract cover cache duration
This commit is contained in:
@@ -4,6 +4,8 @@ defmodule MusicLibraryWeb.CoverController do
|
|||||||
alias MusicLibrary.Records
|
alias MusicLibrary.Records
|
||||||
alias MusicLibrary.Records.Cover
|
alias MusicLibrary.Records.Cover
|
||||||
|
|
||||||
|
@cache_duration 60 * 60 * 24
|
||||||
|
|
||||||
def show(conn, %{"record_id" => record_id, "size" => size}) do
|
def show(conn, %{"record_id" => record_id, "size" => size}) do
|
||||||
case Records.get_cover(record_id) do
|
case Records.get_cover(record_id) do
|
||||||
nil ->
|
nil ->
|
||||||
@@ -12,7 +14,7 @@ defmodule MusicLibraryWeb.CoverController do
|
|||||||
%{cover_data: cover_data} ->
|
%{cover_data: cover_data} ->
|
||||||
# TODO: find a way to cache computation, or pre-compute thumb and store it
|
# TODO: find a way to cache computation, or pre-compute thumb and store it
|
||||||
{:ok, thumb_data} = Cover.resize(cover_data, String.to_integer(size))
|
{:ok, thumb_data} = Cover.resize(cover_data, String.to_integer(size))
|
||||||
hash = :crypto.hash(:sha256, thumb_data) |> Base.encode16()
|
hash = Cover.hash(thumb_data)
|
||||||
|
|
||||||
case get_req_header(conn, "if-none-match") do
|
case get_req_header(conn, "if-none-match") do
|
||||||
[^hash] -> extend_cache(conn)
|
[^hash] -> extend_cache(conn)
|
||||||
@@ -43,7 +45,7 @@ defmodule MusicLibraryWeb.CoverController do
|
|||||||
# 24 hours
|
# 24 hours
|
||||||
defp extend_cache(conn) do
|
defp extend_cache(conn) do
|
||||||
conn
|
conn
|
||||||
|> put_resp_header("cache-control", "public, max-age=86400")
|
|> put_resp_header("cache-control", "public, max-age=#{@cache_duration}")
|
||||||
|> send_resp(304, "")
|
|> send_resp(304, "")
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -51,7 +53,7 @@ defmodule MusicLibraryWeb.CoverController do
|
|||||||
defp respond_with_cache(conn, cover_data, etag) do
|
defp respond_with_cache(conn, cover_data, etag) do
|
||||||
conn
|
conn
|
||||||
|> put_resp_content_type("image/jpeg", "utf-8")
|
|> put_resp_content_type("image/jpeg", "utf-8")
|
||||||
|> put_resp_header("cache-control", "public, max-age=86400")
|
|> put_resp_header("cache-control", "public, max-age=#{@cache_duration}")
|
||||||
|> put_resp_header("etag", etag)
|
|> put_resp_header("etag", etag)
|
||||||
|> send_resp(200, cover_data)
|
|> send_resp(200, cover_data)
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user