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 142dcb7
Showing 1 changed file with 16 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

Check warning on line 106 in lib/request_cache/plug.ex

View check run for this annotation

Codecov / codecov/patch

lib/request_cache/plug.ex#L106

Added line #L106 was not covered by tests
[] ->
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

0 comments on commit 142dcb7

Please sign in to comment.