-
Notifications
You must be signed in to change notification settings - Fork 346
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
defmodule Tesla.Middleware.PathParams do | ||
@behaviour Tesla.Middleware | ||
|
||
@impl true | ||
def call(env, next, _) do | ||
url = build_url(env.url, env.opts[:path_params]) | ||
Tesla.run(%{env | url: url}, next) | ||
end | ||
|
||
defp build_url(url, nil), do: url | ||
|
||
defp build_url(url, params), | ||
do: Enum.reduce(params, url, fn {k, v}, u -> String.replace(u, ":#{k}", to_string(v)) end) | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
defmodule Tesla.Middleware.PathParamsTest do | ||
use ExUnit.Case, async: true | ||
alias Tesla.Env | ||
|
||
@middleware Tesla.Middleware.PathParams | ||
|
||
test "no params" do | ||
assert {:ok, env} = @middleware.call(%Env{url: "/users/:id"}, [], nil) | ||
assert env.url == "/users/:id" | ||
end | ||
|
||
test "passed params" do | ||
opts = [path_params: [id: 42]] | ||
assert {:ok, env} = @middleware.call(%Env{url: "/users/:id", opts: opts}, [], nil) | ||
assert env.url == "/users/42" | ||
end | ||
end |