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

Add Client.update_middleware/2 function #523

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions lib/tesla/client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,25 @@ defmodule Tesla.Client do
unruntime(client.pre)
end

@doc ~S"""
Given an update function, create a new client by transforming the
list of middlewares for an existing one.

## Examples

iex> middleware = [{Tesla.Middleware.BaseUrl, "https://api.github.com"}]
iex> client = Tesla.client(middleware)
iex> new_client = Tesla.Client.update_middleware(client, &([Tesla.Middleware.JSON] ++ &1))
iex> Tesla.Client.middleware(new_client)
[Tesla.Middleware.JSON, {Tesla.Middleware.BaseUrl, "https://api.github.com"}]
"""
@spec update_middleware(t(), ([middleware()] -> [middleware()])) :: t()
def update_middleware(client, update_fun) do
existing_middleware = middleware(client)
new_middleware = update_fun.(existing_middleware)
Tesla.client(new_middleware, adapter(client))
end

defp unruntime(list) when is_list(list), do: Enum.map(list, &unruntime/1)
defp unruntime({module, :call, [[]]}) when is_atom(module), do: module
defp unruntime({module, :call, [opts]}) when is_atom(module), do: {module, opts}
Expand Down
17 changes: 17 additions & 0 deletions test/tesla/client_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,21 @@ defmodule Tesla.ClientTest do
assert middlewares == Tesla.Client.middleware(client)
end
end

describe "Tesla.Client.update_middleware/2" do
test "updates middleware" do
existing_middleware = [FirstMiddleware]
client = Tesla.client(existing_middleware)

updated_client =
Tesla.Client.update_middleware(
client,
&([{SecondMiddleware, options: :are, fun: 1}] ++ &1)
)

expected_middlewares = [{SecondMiddleware, options: :are, fun: 1}, FirstMiddleware]

assert expected_middlewares == Tesla.Client.middleware(updated_client)
end
end
end