Skip to content

Commit 606e5f7

Browse files
authored
Remove ducpicate application/json header (#27)
* Tesla.Middleware.JSON already includes the {"Content-Type", "application/json"} header. Duplicate headers may trigger a search error. * Implement a check to verify if the application/json header is already present. * Create a new Header middleware to manage Content-Type headers and prevent duplicates.
1 parent eba23e4 commit 606e5f7

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/meilisearch/client.ex

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ defmodule Meilisearch.Client do
3434
Tesla.Middleware.JSON,
3535
Tesla.Middleware.PathParams,
3636
{Tesla.Middleware.BearerAuth, token: key},
37-
{Tesla.Middleware.Headers,
38-
[{"Content-Type", "application/json"}, {"User-Agent", Meilisearch.qualified_version()}]},
37+
Meilisearch.Middleware.Headers,
3938
{Tesla.Middleware.Timeout, timeout: timeout},
4039
{Tesla.Middleware.Logger,
4140
log_level: log_level, debug: debug, filter_headers: ["authorization"]}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
defmodule Meilisearch.Middleware.Headers do
2+
@moduledoc """
3+
Middleware for dealing with Meilisearch request headers.
4+
Ensures there is exactly one Content-Type: application/json header
5+
and adds the User-Agent header.
6+
"""
7+
@behaviour Tesla.Middleware
8+
9+
@impl Tesla.Middleware
10+
def call(env, next, _options) do
11+
env
12+
|> Tesla.put_header("user-agent", Meilisearch.qualified_version())
13+
|> ensure_single_content_type()
14+
|> Tesla.run(next)
15+
end
16+
17+
# Ensure there is exactly one Content-Type: application/json header
18+
defp ensure_single_content_type(%Tesla.Env{headers: headers} = env) do
19+
# Filter out all headers that are not content-type
20+
filtered_headers = Enum.filter(headers, fn {header, _value} ->
21+
String.downcase(header) != "content-type"
22+
end)
23+
24+
# Create a new environment with only non-content-type headers
25+
env = %{env | headers: filtered_headers}
26+
27+
# Add a single content-type header
28+
Tesla.put_header(env, "content-type", "application/json")
29+
end
30+
end

0 commit comments

Comments
 (0)