1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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)
69 adapter = Application.get_env(:tesla, :adapter)
71 client = Tesla.client(adapter_middlewares(adapter), adapter)
75 request(client, request)
82 @spec request(Client.t(), keyword()) :: {:ok, Env.t()} | {:error, any()}
83 def request(client, request), do: Tesla.request(client, request)
85 defp build_request(method, headers, options, url, body, params) do
87 |> Builder.method(method)
88 |> Builder.headers(headers)
89 |> Builder.opts(options)
91 |> Builder.add_param(:body, :body, body)
92 |> Builder.add_param(:query, :query, params)
93 |> Builder.convert_to_keyword()
96 @prefix Pleroma.Gun.ConnectionPool
97 defp maybe_limit(fun, Tesla.Adapter.Gun, opts) do
98 ConcurrentLimiter.limit(:"#{@prefix}.#{opts[:pool] || :default}", fun)
101 defp maybe_limit(fun, _, _) do
105 defp adapter_middlewares(Tesla.Adapter.Gun) do
106 [Tesla.Middleware.FollowRedirects, Pleroma.Tesla.Middleware.ConnectionPool]
109 defp adapter_middlewares(_), do: []