diff options
| author | Aotrix <[email protected]> | 2025-11-16 21:07:44 +0100 |
|---|---|---|
| committer | Aotrix <[email protected]> | 2025-11-16 21:07:44 +0100 |
| commit | e006ece3289c848ca2975f06386d6a2a51bdb67f (patch) | |
| tree | 1d72ae49b6a14cd43b3dec06ff78a7ae6d628f3c /subprojects/battleNetApi/include/hearthstoneApi.hpp | |
| parent | 832e276e94d4d5a30885e6e352ffdd19f4f16f04 (diff) | |
Refactored JSON value retrieval
Diffstat (limited to 'subprojects/battleNetApi/include/hearthstoneApi.hpp')
| -rw-r--r-- | subprojects/battleNetApi/include/hearthstoneApi.hpp | 26 |
1 files changed, 25 insertions, 1 deletions
diff --git a/subprojects/battleNetApi/include/hearthstoneApi.hpp b/subprojects/battleNetApi/include/hearthstoneApi.hpp index bbcc8c7..c11acc7 100644 --- a/subprojects/battleNetApi/include/hearthstoneApi.hpp +++ b/subprojects/battleNetApi/include/hearthstoneApi.hpp @@ -1,17 +1,41 @@ #pragma once #include "token.hpp" +#include <iostream> +#include <regex> #include <string> class HearthstoneApi { public: HearthstoneApi(Token &&iToken); - std::uint64_t numberOfCards(); + std::uint64_t numberOfCards(const std::string &iApiResponse) const; private: std::string authorizationHeader(); std::string makeApiRequest(const std::string &iUrl) const; static size_t curlCallbackStringOutput(void *iContent, size_t iSize, size_t iNmemb, std::string *iS); + /** + * @brief + * @param[in] iJsonContent The std::string which contains Json (Battle.net API response for instance) + * @param[in] iKeyValueRegex The regex used to retrieve value from (key, value) pair + * An example: "\"cardCount\":(\\d+)" + */ + template <typename T> T valueInJson(const std::string &iJsonContent, const std::string &iKeyValueRegex) const { + const std::regex iRegex{iKeyValueRegex}; + std::smatch aMatches; + if (std::regex_search(iJsonContent, aMatches, iRegex)) { + const std::string kValueString{aMatches[1].str()}; + T aValue; + const auto kConversionStatus = + std::from_chars(kValueString.data(), kValueString.data() + kValueString.size(), aValue); + if (kConversionStatus.ec == std::errc{}) { + return aValue; + } + } + std::cerr << std::format("Unable to find value with regex: '{}'\n", iKeyValueRegex); + return 0; + } + Token mToken; std::string mAuthorizationHeader; //<! Bearer authorization string for OAuth 2.0 header |
