Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: json decoder middleware for uppercase content type #685

Merged
merged 1 commit into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/tesla/middleware/json.ex
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,15 @@ defmodule Tesla.Middleware.JSON do

defp decodable_content_type?(env, opts) do
case Tesla.get_header(env, "content-type") do
nil -> false
content_type -> Enum.any?(content_types(opts), &String.starts_with?(content_type, &1))
nil ->
false

content_type ->
content_type = String.downcase(content_type)

opts
|> content_types()
|> Enum.any?(&String.starts_with?(content_type, &1))
end
end

Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ defmodule Tesla.Mixfile do
use Mix.Project

@source_url "https://github.com/teamon/tesla"
@version "1.10.1"
@version "1.10.2"

def project do
[
Expand Down
9 changes: 9 additions & 0 deletions test/tesla/middleware/json_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ defmodule Tesla.Middleware.JsonTest do
adapter fn env ->
{status, headers, body} =
case env.url do
# GET https://testlajson.free.beeceptor.com/todos to see the response
"/uppercased-content-type" ->
{200, [{"content-type", "application/JSON"}], "{\"value\": 123}"}

"/decode" ->
{200, [{"content-type", "application/json"}], "{\"value\": 123}"}

Expand Down Expand Up @@ -48,6 +52,11 @@ defmodule Tesla.Middleware.JsonTest do
end
end

test "decoding json with insensitive content type" do
assert {:ok, env} = Client.get("/uppercased-content-type")
assert env.body == %{"value" => 123}
end

test "decode JSON body" do
assert {:ok, env} = Client.get("/decode")
assert env.body == %{"value" => 123}
Expand Down
Loading