Add OpenAPI spec for PleromaAPI.PleromaAPIController
[akkoma] / lib / pleroma / http / request_builder.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.HTTP.RequestBuilder do
6 @moduledoc """
7 Helper functions for building Tesla requests
8 """
9
10 alias Pleroma.HTTP.Request
11 alias Tesla.Multipart
12
13 @doc """
14 Creates new request
15 """
16 @spec new(Request.t()) :: Request.t()
17 def new(%Request{} = request \\ %Request{}), do: request
18
19 @doc """
20 Specify the request method when building a request
21 """
22 @spec method(Request.t(), Request.method()) :: Request.t()
23 def method(request, m), do: %{request | method: m}
24
25 @doc """
26 Specify the request method when building a request
27 """
28 @spec url(Request.t(), Request.url()) :: Request.t()
29 def url(request, u), do: %{request | url: u}
30
31 @doc """
32 Add headers to the request
33 """
34 @spec headers(Request.t(), Request.headers()) :: Request.t()
35 def headers(request, headers) do
36 headers_list =
37 if Pleroma.Config.get([:http, :send_user_agent]) do
38 [{"user-agent", Pleroma.Application.user_agent()} | headers]
39 else
40 headers
41 end
42
43 %{request | headers: headers_list}
44 end
45
46 @doc """
47 Add custom, per-request middleware or adapter options to the request
48 """
49 @spec opts(Request.t(), keyword()) :: Request.t()
50 def opts(request, options), do: %{request | opts: options}
51
52 @doc """
53 Add optional parameters to the request
54 """
55 @spec add_param(Request.t(), atom(), atom(), any()) :: Request.t()
56 def add_param(request, :query, :query, values), do: %{request | query: values}
57
58 def add_param(request, :body, :body, value), do: %{request | body: value}
59
60 def add_param(request, :body, key, value) do
61 request
62 |> Map.put(:body, Multipart.new())
63 |> Map.update!(
64 :body,
65 &Multipart.add_field(
66 &1,
67 key,
68 Jason.encode!(value),
69 headers: [{"content-type", "application/json"}]
70 )
71 )
72 end
73
74 def add_param(request, :file, name, path) do
75 request
76 |> Map.put(:body, Multipart.new())
77 |> Map.update!(:body, &Multipart.add_file(&1, path, name: name))
78 end
79
80 def add_param(request, :form, name, value) do
81 Map.update(request, :body, %{name => value}, &Map.put(&1, name, value))
82 end
83
84 def add_param(request, location, key, value) do
85 Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}]))
86 end
87
88 def convert_to_keyword(request) do
89 request
90 |> Map.from_struct()
91 |> Enum.into([])
92 end
93 end