Skip to content

Commit

Permalink
Refactor code, thanks @RedBrumbler!
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenAlex committed Jul 6, 2024
1 parent 6eac190 commit c80e002
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 30 deletions.
52 changes: 23 additions & 29 deletions src/API.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -273,43 +273,37 @@ void NyaAPI::get_path_from_json_api(
SourceData* source,
std::string url,
float timeoutInSeconds,
std::function<void(bool success, std::string url)> finished,
std::string apiKey) {

std::thread([&, source, url, finished, apiKey] {
auto options = WebUtils::URLOptions(url);
options.timeOut = timeoutInSeconds;
if (apiKey != "") { options.headers.emplace("Authorization", apiKey); }
std::function<void(bool success, std::string url)> finished, std::string apiKey
) {
if (finished == nullptr) {
return ERROR("Can't get data async without a callback to use it with");
}
if (source == nullptr) {
ERROR("Source is null");
return finished(false, "");
}

auto response = WebUtils::Get<WebUtils::JsonResponse>(
options
);
auto options = WebUtils::URLOptions(url);
options.timeOut = timeoutInSeconds;
if (apiKey != "") { options.headers.emplace("Authorization", apiKey); }

std::thread([propertyName = source->propertyName, options, finished] {
auto response = WebUtils::Get<WebUtils::JsonResponse>(options);

if (!response.IsSuccessful()) {
if(finished != nullptr) finished(false, "");
return;
}
if (!response.IsSuccessful()) return finished(false, "");

auto result = response.responseData.has_value();
if (!result) {
if(finished != nullptr) finished(false, "");
return;
}
if (!result) return finished(false, "");

auto& document = response.responseData.value();
if(document.HasParseError() || !document.IsObject()) {
if(finished != nullptr) finished(false, "");
return;
}
if(document.HasParseError() || !document.IsObject()) return finished(false, "");

std::string url = "";
if(document.HasMember(source->propertyName))
{
url = document.FindMember(source->propertyName)->value.GetString();
if(finished != nullptr) finished(true, url);
auto itr = document.FindMember(propertyName);
if (itr != document.MemberEnd() && itr->value.IsString()) {
std::string url(itr->value.GetString(), itr->value.GetStringLength());
return finished(true, url);
} else {
if(finished != nullptr) finished(false, "");
return;
return finished(false, "");
}
}).detach();
}
Expand Down
2 changes: 1 addition & 1 deletion src/Utils/Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ namespace Nya::Utils {
return;
}

auto data = response.responseData.value();
auto& data = response.responseData.value();
if (data.size() == 0) {
ERROR("Failed to get the data, data size is 0");
if (onFinished) {
Expand Down

0 comments on commit c80e002

Please sign in to comment.