diff --git a/lib/request_cache/plug.ex b/lib/request_cache/plug.ex index 0da3cc7..703e50d 100644 --- a/lib/request_cache/plug.ex +++ b/lib/request_cache/plug.ex @@ -16,6 +16,8 @@ defmodule RequestCache.Plug do # This is compile time so we can check quicker @graphql_paths RequestCache.Config.graphql_paths() @request_cache_header "rc-cache-status" + @json_regex ~r/^(\[|\{)(.*|\n)*(\]|\})$/ + @html_regex ~r//i @impl Plug def init(opts), do: opts @@ -95,10 +97,23 @@ defmodule RequestCache.Plug do conn |> Plug.Conn.halt() |> Plug.Conn.put_resp_header(@request_cache_header, "HIT") - |> Plug.Conn.put_resp_content_type("application/json") + |> maybe_put_content_type(result) |> Plug.Conn.send_resp(200, result) end + defp maybe_put_content_type(conn, result) do + case Plug.Conn.get_resp_header(conn, "content-type") do + [_ | _] -> conn + [] -> + cond do + result =~ @json_regex -> Plug.Conn.put_resp_content_type(conn, "application/json") + result =~ @html_regex -> Plug.Conn.put_resp_content_type(conn, "text/html") + + true -> conn + end + end + end + defp rest_cache_key(%Plug.Conn{request_path: path, query_string: query_string}) do Util.create_key(path, query_string) end diff --git a/test/request_cache_plug_test.exs b/test/request_cache_plug_test.exs index 5ee9f3e..2ab7321 100644 --- a/test/request_cache_plug_test.exs +++ b/test/request_cache_plug_test.exs @@ -162,6 +162,36 @@ defmodule RequestCachePlugTest do ] end + test "allows for for custom content-type header and returns it when served from the cache", %{ + caller_pid: pid + } do + route = "/my_route/:param" + assert %Plug.Conn{resp_headers: uncached_headers} = + :get + |> conn(route) + |> RequestCache.Support.Utils.ensure_default_opts() + |> put_private(:call_pid, pid) + |> Router.call([]) + + assert uncached_headers === [ + {"cache-control", "max-age=0, private, must-revalidate"} + ] + + assert %Plug.Conn{resp_headers: resp_headers} = + :get + |> conn(route) + |> RequestCache.Support.Utils.ensure_default_opts() + |> put_private(:call_pid, pid) + |> put_resp_content_type("text/html") + |> Router.call([]) + + assert resp_headers === [ + {"cache-control", "max-age=0, private, must-revalidate"}, + {"content-type", "text/html; charset=utf-8"}, + {"rc-cache-status", "HIT"} + ] + end + test "allows you to use `cache` key inside opts to override specific cache for a request" do end end