Current section

Files

Jump to
merchant lib merchant client.ex
Raw

lib/merchant/client.ex

defmodule Merchant.Client do
@moduledoc """
Client for the Merchant API.
"""
@api_version "2024-09-01"
@type method :: :head | :get | :delete | :trace | :options | :post | :put | :patch
@type error :: {:error, Tesla.Env.t()}
@spec client :: Tesla.Client.t()
def client do
base_url = Application.get_env(:merchant, :base_url)
api_key = Application.get_env(:merchant, :api_key)
if is_nil(base_url) do
raise "REVOLUT_BASE_URL is not set"
end
if is_nil(api_key) do
raise "REVOLUT_API_KEY is not set"
end
Tesla.client([
{Tesla.Middleware.BaseUrl, base_url},
{Tesla.Middleware.Headers,
[
{"Authorization", "Bearer #{api_key}"},
{"Revolut-Api-Version", @api_version}
]},
{Tesla.Middleware.JSON, engine: JSON}
])
end
@spec req(method(), String.t(), term(), Keyword.t(), Keyword.t(), Keyword.t()) ::
{:ok, term()} | error()
def req(method, path, body \\ nil, params \\ [], headers \\ [], opts \\ []) do
case Tesla.request(client(),
method: method,
url: path,
body: body,
query: params,
headers: headers,
opts: opts
) do
{:ok, %Tesla.Env{status: status, body: body}} when status < 400 ->
{:ok, body}
{:error, error} ->
{:error, error}
end
end
@spec req!(method(), String.t(), term(), Keyword.t(), Keyword.t(), Keyword.t()) :: term()
def req!(method, path, body \\ nil, params \\ [], headers \\ [], opts \\ []) do
case req(method, path, body, params, headers, opts) do
{:ok, body} -> body
{:error, error} -> raise error
end
end
end