Merge pull request 'Correct og:description tag in static-fe' (#373) from sfr/akkoma...
[akkoma] / lib / pleroma / http.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.HTTP do
6 @moduledoc """
7 Wrapper for `Tesla.request/2`.
8 """
9
10 alias Pleroma.HTTP.AdapterHelper
11 alias Pleroma.HTTP.Request
12 alias Pleroma.HTTP.RequestBuilder, as: Builder
13 alias Tesla.Client
14 alias Tesla.Env
15
16 require Logger
17
18 @type t :: __MODULE__
19 @type method() :: :get | :post | :put | :delete | :head
20
21 @doc """
22 Performs GET request.
23
24 See `Pleroma.HTTP.request/5`
25 """
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)
31
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)
34
35 @doc """
36 Performs POST request.
37
38 See `Pleroma.HTTP.request/5`
39 """
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)
44
45 @doc """
46 Builds and performs http request.
47
48 # Arguments:
49 `method` - :get, :post, :put, :delete, :head
50 `url` - full url
51 `body` - request body
52 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
53 `options` - custom, per-request middleware or adapter options
54
55 # Returns:
56 `{:ok, %Tesla.Env{}}` or `{:error, error}`
57
58 """
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
62 uri = URI.parse(url)
63 adapter_opts = AdapterHelper.options(uri, options || [])
64
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])
69
70 request(client, request)
71 end
72
73 @spec request(Client.t(), keyword()) :: {:ok, Env.t()} | {:error, any()}
74 def request(client, request), do: Tesla.request(client, request)
75
76 defp build_request(method, headers, options, url, body, params) do
77 Builder.new()
78 |> Builder.method(method)
79 |> Builder.headers(headers)
80 |> Builder.opts(options)
81 |> Builder.url(url)
82 |> Builder.add_param(:body, :body, body)
83 |> Builder.add_param(:query, :query, params)
84 |> Builder.convert_to_keyword()
85 end
86 end