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.RequestBuilder do
7 Helper functions for building Tesla requests
10 alias Pleroma.HTTP.Request
16 @spec new(Request.t()) :: Request.t()
17 def new(%Request{} = request \\ %Request{}), do: request
20 Specify the request method when building a request
22 @spec method(Request.t(), Request.method()) :: Request.t()
23 def method(request, m), do: %{request | method: m}
26 Specify the request method when building a request
28 @spec url(Request.t(), Request.url()) :: Request.t()
29 def url(request, u), do: %{request | url: u}
32 Add headers to the request
34 @spec headers(Request.t(), Request.headers()) :: Request.t()
35 def headers(request, headers) do
37 if Pleroma.Config.get([:http, :send_user_agent]) do
38 [{"user-agent", Pleroma.Application.user_agent()} | headers]
43 %{request | headers: headers_list}
47 Add custom, per-request middleware or adapter options to the request
49 @spec opts(Request.t(), keyword()) :: Request.t()
50 def opts(request, options), do: %{request | opts: options}
53 Add optional parameters to the request
55 @spec add_param(Request.t(), atom(), atom(), any()) :: Request.t()
56 def add_param(request, :query, :query, values), do: %{request | query: values}
58 def add_param(request, :body, :body, value), do: %{request | body: value}
60 def add_param(request, :body, key, value) do
62 |> Map.put(:body, Multipart.new())
69 headers: [{"content-type", "application/json"}]
74 def add_param(request, :file, name, path) do
76 |> Map.put(:body, Multipart.new())
77 |> Map.update!(:body, &Multipart.add_file(&1, path, name: name))
80 def add_param(request, :form, name, value) do
81 Map.update(request, :body, %{name => value}, &Map.put(&1, name, value))
84 def add_param(request, location, key, value) do
85 Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}]))
88 def convert_to_keyword(request) do