Skip to content
Tymon Tobolski edited this page Oct 2, 2017 · 18 revisions

Usage examples

Pass Phoenix x-request-id header to upstream resources (by @timbuchwaldt)

defmodule MyAPI do
  use Tesla

  plug Tesla.Middleware.BaseUrl, "http://127.0.0.1:4000"

  def foo(client, login) do
    get(client, "/foo")
  end

  def client(%{resp_headers: resp_headers}) do
    {"x-request-id", id} = resp_headers
    |> List.keyfind("x-request-id", 0)

    Tesla.build_client [
      {PhoenixRequestIDMiddleware, id}
    ]
  end
end

defmodule PhoenixRequestIDMiddleware do
  def call(env, next, opts) do
    env
    |> add_request_id(opts)
    |> IO.inspect
    |> Tesla.run(next)
  end

  def add_request_id(env, id) do
    Map.update!(env, :headers, &Map.merge(&1, %{"x-request-id" => id}))
  end
end

Custom middleware for Appsignal

defmodule Tesla.Middleware.Appsignal do
  import Appsignal.Instrumentation.Helpers, only: [instrument: 3]

  def call(env, next, _opts) do
    verb = env.method |> to_string |> String.upcase
    instrument "net.http", "#{verb} #{env.url}", fn ->
      Tesla.run(env, next)
    end
  end
end