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

Introduce Tesla.client/1 & Tesla.client/2 #244

Merged
merged 5 commits into from
Sep 7, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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
27 changes: 3 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ Consider the following case: GitHub API can be accessed using OAuth token author
We can't use `plug Tesla.Middleware.Headers, [{"authorization", "token here"}]`
since this would be compiled only once and there is no way to insert dynamic user token.

Instead, we can use `Tesla.build_client` to create a dynamic middleware function:
Instead, we can use `Tesla.client` to create a dynamic middleware function:

```elixir
defmodule GitHub do
Expand All @@ -139,9 +139,9 @@ defmodule GitHub do

# build dynamic client based on runtime arguments
def client(token) do
Tesla.build_client [
Tesla.client([
{Tesla.Middleware.Headers, [{"authorization", "token: " <> token }]}
]
])
end
end
```
Expand All @@ -157,27 +157,6 @@ GitHub.issues()
client |> GitHub.issues()
```

The `Tesla.build_client` function can take two arguments: `pre` and `post` middleware.
The first list (`pre`) will be included before any other middleware. In case there is a need
to inject middleware at the end you can pass a second list (`post`). It will be put just
before adapter. In fact, one can even dynamically override the adapter.

For example, a private (per user) cache could be implemented as:

```elixir
def new(user) do
Tesla.build_client [], [
fn env, next ->
case my_private_cache.fetch(user, env) do
{:ok, env} -> {:ok, env} # return cached response
:error -> Tesla.run(env, next) # make real request
end
end
end
end
```


## Adapters

Tesla supports multiple HTTP adapter that do the actual HTTP request processing.
Expand Down
77 changes: 60 additions & 17 deletions lib/tesla.ex
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,18 @@ defmodule Tesla.Env do
end

defmodule Tesla.Client do
@type adapter :: module | {atom, Tesla.Env.opts()}
@type middleware :: module | {atom, Tesla.Env.opts()}

@type t :: %__MODULE__{
pre: Tesla.Env.stack(),
post: Tesla.Env.stack()
post: Tesla.Env.stack(),
adapter: adapter | nil
}
defstruct fun: nil,
pre: [],
post: []
post: [],
adapter: nil
end

defmodule Tesla.Middleware do
Expand All @@ -86,9 +91,9 @@ defmodule Tesla.Middleware do

plug Tesla.Middleware.BaseUrl, "https://example.com"

or inside tuple in case of dynamic middleware (`Tesla.build_client/2`)
or inside tuple in case of dynamic middleware (`Tesla.client/1`)

Tesla.build_client([{Tesla.Middleware.BaseUrl, "https://example.com"}])
Tesla.client([{Tesla.Middleware.BaseUrl, "https://example.com"}])

## Writing custom middleware

Expand Down Expand Up @@ -298,13 +303,14 @@ defmodule Tesla do

defp prepare(module, %{pre: pre, post: post} = client, options) do
env = struct(Env, options ++ [__module__: module, __client__: client])
stack = pre ++ module.__middleware__ ++ post ++ [effective_adapter(module)]
stack = pre ++ module.__middleware__ ++ post ++ [effective_adapter(module, client)]
{env, stack}
end

@doc false
def effective_adapter(module) do
with nil <- adapter_per_module_from_config(module),
def effective_adapter(module, client \\ %Tesla.Client{}) do
with nil <- client.adapter,
nil <- adapter_per_module_from_config(module),
nil <- adapter_per_module(module),
nil <- adapter_from_config() do
adapter_default()
Expand Down Expand Up @@ -421,26 +427,63 @@ defmodule Tesla do
def put_body(%Env{} = env, body), do: %{env | body: body}

@doc """
Dynamically build client from list of middlewares.
Dynamically build client from list of middlewares and/or adapter.

```
defmodule ExampleAPI do
use Tesla
# add dynamic middleware
client = Tesla.client([{Tesla.Middleware.Headers, [{"authorization", token}]}])
Tesla.get(client, "/path")

# configure adapter in runtime
client = Tesla.client([], Tesla.Adapter.Hackney)
client = Tesla.client([], {Tesla.Adapter.Hackney, pool: :my_pool)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing }

Tesla.get(client, "/path")

# complete module example
defmodule MyApi do
# note there is no need for `use Tesla`

@middleware [
{Tesla.Middleware.BaseUrl, "https://example.com"},
Tesla.Middleware.JSON,
Tesla.Middleware.Logger
]

@adapter Tesla.Adapter.Hackney

def new(opts) do
# do any middleware manipulation you need
middleware = [
{Tesla.Middleware.BasicAuth, username: opts[:username], password: opts[:password]}
] ++ @middleware

# allow configuring adapter in runtime
adapter = opts[:adapter] || @adapter

# use Tesla.client/2 to put it all together
Tesla.client(middleware, adapter)
end

def new(token) do
Tesla.build_client([
{Tesla.Middleware.Headers, [{"authorization", token}]
])
def get_something(client, id) do
# pass client directly to Tesla.get/2
Tesla.get(client, "/something/\#{id}")
# ...
end
end

client = ExampleAPI.new(token: "abc")
client |> ExampleAPI.get("/me")
client = MyApi.new(username: "admin", password: "secret")
MyApi.get_something(client, 42)
```
"""
@since "1.2.0"
@spec client([Tesla.Client.middleware()], Tesla.Client.adapter()) :: Tesla.Client.t()
def client(middleware, adapter \\ nil), do: Tesla.Builder.client(middleware, [], adapter)

@deprecated "Use client/1 or client/2 instead"
def build_client(pre, post \\ []), do: Tesla.Builder.client(pre, post)

def build_adapter(fun), do: Tesla.Builder.client([], [fn env, _next -> fun.(env) end])
@deprecated "Use client/1 or client/2 instead"
def build_adapter(fun), do: Tesla.Builder.client([], [], fun)

def build_url(url, []), do: url

Expand Down
10 changes: 9 additions & 1 deletion lib/tesla/builder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,15 @@ defmodule Tesla.Builder do
end
end

def client(pre, post), do: %Tesla.Client{pre: runtime(pre), post: runtime(post)}
def client(pre, post, adapter \\ nil)

def client(pre, post, nil) do
%Tesla.Client{pre: runtime(pre), post: runtime(post)}
end

def client(pre, post, adapter) do
%Tesla.Client{pre: runtime(pre), post: runtime(post), adapter: runtime(adapter)}
end

@default_opts []

Expand Down
2 changes: 1 addition & 1 deletion lib/tesla/middleware/basic_auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ defmodule Tesla.Middleware.BasicAuth do

# dynamic user & pass
def new(username, password, opts \\\\ %{}) do
Tesla.build_client [
Tesla.client [
{Tesla.Middleware.BasicAuth, Map.merge(%{username: username, password: password}, opts)}
]
end
Expand Down
2 changes: 1 addition & 1 deletion lib/tesla/middleware/digest_auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ defmodule Tesla.Middleware.DigestAuth do
use Tesla

def client(username, password, opts \\ %{}) do
Tesla.build_client [
Tesla.client [
{Tesla.Middleware.DigestAuth, Map.merge(%{username: username, password: password}, opts)}
]
end
Expand Down
2 changes: 1 addition & 1 deletion lib/tesla/migration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ defmodule Tesla.Migration do
message: """

Using anonymous function as client has been removed.
Use `Tesla.build_client` instead
Use `Tesla.client/2` instead

See #{@breaking_client_fun}
"""
Expand Down
4 changes: 2 additions & 2 deletions test/tesla/middleware/basic_auth_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ defmodule Tesla.Middleware.BasicAuthTest do
end

def client(username, password, opts \\ %{}) do
Tesla.build_client([
Tesla.client([
{
Tesla.Middleware.BasicAuth,
Map.merge(
Expand All @@ -26,7 +26,7 @@ defmodule Tesla.Middleware.BasicAuthTest do
end

def client() do
Tesla.build_client([Tesla.Middleware.BasicAuth])
Tesla.client([Tesla.Middleware.BasicAuth])
end
end

Expand Down
4 changes: 2 additions & 2 deletions test/tesla/middleware/digest_auth_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ defmodule Tesla.Middleware.DigestAuthTest do
end

def client(username, password, opts \\ %{}) do
Tesla.build_client([
Tesla.client([
{
Tesla.Middleware.DigestAuth,
Map.merge(
Expand All @@ -48,7 +48,7 @@ defmodule Tesla.Middleware.DigestAuthTest do
use Tesla

def client do
Tesla.build_client([
Tesla.client([
{Tesla.Middleware.DigestAuth, nil}
])
end
Expand Down
18 changes: 5 additions & 13 deletions test/tesla_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -149,22 +149,14 @@ defmodule TeslaTest do
end
end

test "override adapter - Tesla.build_client" do
test "override adapter - Tesla.client" do
client =
Tesla.build_client([], [
fn env, _next ->
Tesla.client(
[],
fn env ->
{:ok, %{env | body: "new"}}
end
])

assert {:ok, %{body: "new"}} = DynamicClient.help(client)
end

test "override adapter - Tesla.build_adapter" do
client =
Tesla.build_adapter(fn env ->
{:ok, %{env | body: "new"}}
end)
)

assert {:ok, %{body: "new"}} = DynamicClient.help(client)
end
Expand Down