From 142dcb777f5d5a514ab35d747c6ba7c781819e7e Mon Sep 17 00:00:00 2001 From: MikaAK Date: Mon, 21 Aug 2023 23:06:29 -0400 Subject: [PATCH] fix: make sure we detect content type and set properly or allow it to pass through if set --- lib/request_cache/plug.ex | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) 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