1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTTP do
7 Wrapper for `Tesla.request/2`.
10 alias Pleroma.HTTP.AdapterHelper
11 alias Pleroma.HTTP.Request
12 alias Pleroma.HTTP.RequestBuilder, as: Builder
19 @type method() :: :get | :post | :put | :delete | :head
24 See `Pleroma.HTTP.request/5`
26 @spec get(Request.url() | nil, Request.headers(), keyword()) ::
27 nil | {:ok, Env.t()} | {:error, any()}
28 def get(url, headers \\ [], options \\ [])
29 def get(nil, _, _), do: nil
30 def get(url, headers, options), do: request(:get, url, "", headers, options)
32 @spec head(Request.url(), Request.headers(), keyword()) :: {:ok, Env.t()} | {:error, any()}
33 def head(url, headers \\ [], options \\ []), do: request(:head, url, "", headers, options)
36 Performs POST request.
38 See `Pleroma.HTTP.request/5`
40 @spec post(Request.url(), String.t(), Request.headers(), keyword()) ::
41 {:ok, Env.t()} | {:error, any()}
42 def post(url, body, headers \\ [], options \\ []),
43 do: request(:post, url, body, headers, options)
46 Builds and performs http request.
49 `method` - :get, :post, :put, :delete, :head
52 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
53 `options` - custom, per-request middleware or adapter options
56 `{:ok, %Tesla.Env{}}` or `{:error, error}`
59 @spec request(method(), Request.url(), String.t(), Request.headers(), keyword()) ::
60 {:ok, Env.t()} | {:error, any()}
61 def request(method, url, body, headers, options) when is_binary(url) do
63 adapter_opts = AdapterHelper.options(uri, options || [])
65 options = put_in(options[:adapter], adapter_opts)
66 params = options[:params] || []
67 request = build_request(method, headers, options, url, body, params)
68 client = Tesla.client([Tesla.Middleware.FollowRedirects, Tesla.Middleware.Telemetry])
70 request(client, request)
73 @spec request(Client.t(), keyword()) :: {:ok, Env.t()} | {:error, any()}
74 def request(client, request), do: Tesla.request(client, request)
76 defp build_request(method, headers, options, url, body, params) do
78 |> Builder.method(method)
79 |> Builder.headers(headers)
80 |> Builder.opts(options)
82 |> Builder.add_param(:body, :body, body)
83 |> Builder.add_param(:query, :query, params)
84 |> Builder.convert_to_keyword()