Skip to content

Commit

Permalink
PathParams middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
teamon committed Dec 17, 2018
1 parent 14124e1 commit 21f8a3e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/tesla/middleware/path_params.ex
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
17 changes: 17 additions & 0 deletions test/tesla/middleware/path_params_test.exs
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

0 comments on commit 21f8a3e

Please sign in to comment.