Usage

setup

Setup

First of all, we need to install tesla_keys and all dependencies to work with tesla:

Mix.install(~w[tesla jason tesla_keys]a)

using

Using

Let's create an HTTP client to consume the {JSON} Placeholder fake API. To learn more about it, see the guide.

defmodule Client do
  use Tesla

  plug Tesla.Middleware.BaseUrl, "https://jsonplaceholder.typicode.com/"
  # middleware for remapping request and response body keys
  plug TeslaKeys.Middleware.Remapper, keys: [{"body", "content"}]
  # middleware for case conversion of the request and response body keys
  plug TeslaKeys.Middleware.Case
  plug Tesla.Middleware.Logger
  plug Tesla.Middleware.PathParams
  plug Tesla.Middleware.JSON

  def list_posts() do
    get("/posts")
  end

  def update_post(id, body) do
    params = [id: id]
    put("/posts/:id", body, opts: [path_params: params])
  end
end

In the example above, the {JSON} Placeholder expects the post body to have the following JSON structure:

{
  "id": 1,
  "title": "...",
  "body": "...",
  "userId": 1
}

But when we use the TeslaKeys plugs to handle our request and response, we make some changes to the body data along the way, getting the following structure relative to the previous one:

%{
  "id" => 1,
  "title" => "...",
  "content" => "...",
  "user_id" => 1
}

That way, when we use TeslaKeys.Middleware.Remapper we are remapping the body key to content and when we use TeslaKeys.Middleware.Case, we are doing the case conversion.

params = %{"title" => "TeslaKeys", "content" => "Manipulates body keys", "user_id" => 1}

with {:ok, %{body: body}} <- Client.update_post(1, params) do
  body
end

When running the above request, we noticed that to satisfy the structure expected by the API, the request was converted when sent like:

# requested as:
%{"title" => "TeslaKeys", "content" => "Manipulates body keys", "user_id" => 1}
# converted to:
%{"title" => "TeslaKeys", "body" => "Manipulates body keys", "userId" => 1}

but when responded, it was converted again to get the desired result:

# responded as:
%{"id" => 1, "title" => "TeslaKeys", "body" => "Manipulates body keys", "userId" => 1}
# converted to:
%{"id" => 1, "title" => "TeslaKeys", "content" => "Manipulates body keys", "user_id" => 1}