Move URI building for GET requets to add_parameters_to_uri().

This commit is contained in:
tastytea 2020-01-08 17:51:53 +01:00
parent 6b5936a4b6
commit c93810e241
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 62 additions and 44 deletions

View File

@ -173,6 +173,16 @@ private:
* @since 0.1.0
*/
void setup_curl();
/*!
* @brief Add parameters to URI.
*
* @param uri Reference to the URI.
* @param parameters The parametermap.
*
* @since 0.1.0
*/
void add_parameters_to_uri(string &uri, const parametermap &parameters);
};
} // namespace mastodonpp

View File

@ -84,50 +84,7 @@ answer_type CURLWrapper::make_request(const http_method &method, string uri,
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
code = curl_easy_setopt(_connection, CURLOPT_HTTPGET, 1L);
for (const auto &param : parameters)
{
static constexpr array replace_in_uri
{
"id", "nickname", "nickname_or_id",
"hashtag", "permission_group"
};
if (any_of(replace_in_uri.begin(), replace_in_uri.end(),
[&param](const auto &s) { return s == param.first; }))
{
const auto pos{uri.find('<')};
if (pos != string::npos)
{
uri.replace(pos, param.first.size() + 2,
get<string_view>(param.second));
}
continue;
}
static bool first{true};
if (first)
{
uri += "?";
first = false;
}
else
{
uri += "&";
}
if (holds_alternative<string_view>(param.second))
{
((uri += param.first) += "=") += get<string_view>(param.second);
}
else
{
for (const auto &arg : get<vector<string_view>>(param.second))
{
((uri += param.first) += "[]=") += arg;
if (arg != *get<vector<string_view>>(param.second).rbegin())
{
uri += "&";
}
}
}
}
add_parameters_to_uri(uri, parameters);
break;
}
@ -266,4 +223,55 @@ void CURLWrapper::setup_curl()
curl_easy_setopt(_connection, CURLOPT_MAXREDIRS, 10L);
}
void CURLWrapper::add_parameters_to_uri(string &uri,
const parametermap &parameters)
{
// Replace <ID> with the value of parameter “id” and so on.
for (const auto &param : parameters)
{
static constexpr array replace_in_uri
{
"id", "nickname", "nickname_or_id",
"hashtag", "permission_group"
};
if (any_of(replace_in_uri.begin(), replace_in_uri.end(),
[&param](const auto &s) { return s == param.first; }))
{
const auto pos{uri.find('<')};
if (pos != string::npos)
{
uri.replace(pos, param.first.size() + 2,
get<string_view>(param.second));
continue;
}
}
static bool first{true};
if (first)
{
uri += "?";
first = false;
}
else
{
uri += "&";
}
if (holds_alternative<string_view>(param.second))
{
((uri += param.first) += "=") += get<string_view>(param.second);
}
else
{
for (const auto &arg : get<vector<string_view>>(param.second))
{
((uri += param.first) += "[]=") += arg;
if (arg != *get<vector<string_view>>(param.second).rbegin())
{
uri += "&";
}
}
}
}
}
} // namespace mastodonpp