Skip to content

Commit

Permalink
fix: make sure we detect content type and set properly or allow it to…
Browse files Browse the repository at this point in the history
… pass through if set
  • Loading branch information
MikaAK committed Aug 22, 2023
1 parent c366940 commit 965de96
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/request_cache/plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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/<!DOCTYPE\s+html>/i

@impl Plug
def init(opts), do: opts
Expand Down Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions test/request_cache_plug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 965de96

Please sign in to comment.