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
11 Specify the request method when building a request
15 - request (Map) - Collected request options
16 - m (atom) - Request method
22 @spec method(map(), atom) :: map()
23 def method(request, m) do
24 Map.put_new(request, :method, m)
28 Specify the request method when building a request
32 - request (Map) - Collected request options
33 - u (String) - Request URL
39 @spec url(map(), String.t()) :: map()
40 def url(request, u) do
41 Map.put_new(request, :url, u)
45 Add headers to the request
47 @spec headers(map(), list(tuple)) :: map()
48 def headers(request, header_list) do
50 if Pleroma.Config.get([:http, :send_user_agent]) do
51 header_list ++ [{"User-Agent", Pleroma.Application.user_agent()}]
56 Map.put_new(request, :headers, header_list)
60 Add custom, per-request middleware or adapter options to the request
62 @spec opts(map(), Keyword.t()) :: map()
63 def opts(request, options) do
64 Map.put_new(request, :opts, options)
68 Add optional parameters to the request
72 - request (Map) - Collected request options
73 - definitions (Map) - Map of parameter name to parameter location.
74 - options (KeywordList) - The provided optional parameters
80 @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map()
81 def add_optional_params(request, _, []), do: request
83 def add_optional_params(request, definitions, [{key, value} | tail]) do
85 %{^key => location} ->
87 |> add_param(location, key, value)
88 |> add_optional_params(definitions, tail)
91 add_optional_params(request, definitions, tail)
96 Add optional parameters to the request
100 - request (Map) - Collected request options
101 - location (atom) - Where to put the parameter
102 - key (atom) - The name of the parameter
103 - value (any) - The value of the parameter
109 @spec add_param(map(), atom, atom, any()) :: map()
110 def add_param(request, :query, :query, values), do: Map.put(request, :query, values)
112 def add_param(request, :body, :body, value), do: Map.put(request, :body, value)
114 def add_param(request, :body, key, value) do
116 |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0)
119 &Tesla.Multipart.add_field(
122 Jason.encode!(value),
123 headers: [{:"Content-Type", "application/json"}]
128 def add_param(request, :file, name, path) do
130 |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0)
131 |> Map.update!(:body, &Tesla.Multipart.add_file(&1, path, name: name))
134 def add_param(request, :form, name, value) do
136 |> Map.update(:body, %{name => value}, &Map.put(&1, name, value))
139 def add_param(request, location, key, value) do
140 Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}]))