Implement ApiNap::WhoAmI()

Refactor code out into fetch_and_parse() since the
two functions were pretty much the copy paste of
the other. This should simplify the rest of the
missing implementations too.
This commit is contained in:
King_DuckZ 2020-09-03 23:04:41 +01:00
parent 3ff82985c9
commit 2aaf500b66
2 changed files with 40 additions and 16 deletions

View file

@ -44,6 +44,11 @@ Header to_header (const nap::HttpResponse& resp) {
return ret;
}
void fill_base_json (const simdjson::dom::element& doc, BaseJsonReply& out) {
out.generation_timestamp = std::string(doc["generation_timestamp"]);
out.version = static_cast<int>(doc["version"].get_int64());
}
} //unnamed namespace
ApiNap::ApiNap (
@ -66,25 +71,21 @@ ApiNap::ApiNap (
ApiNap::~ApiNap() noexcept = default;
std::pair<Header, Ping> ApiNap::ping() {
auto resp = m_qrest.fetch(m_prefix + g_endpoint_ping);
Ping dataret;
{
std::unique_lock lock(m_json_mutex);
simdjson::dom::element doc = m_json.parse(
reinterpret_cast<const uint8_t*>(resp.body.data()),
resp.body.size()
);
dataret.message = doc["message"];
dataret.generation_timestamp = std::string(doc["generation_timestamp"]);
dataret.version = static_cast<int>(int64_t(doc["version"]));
return fetch_and_parse<Ping>(
g_endpoint_ping,
[](const simdjson::dom::element& doc, Ping& out) {
out.message = doc["message"];
}
return {to_header(resp), std::move(dataret)};
);
}
std::pair<Header, WhoAmI> ApiNap::who_am_i() {
return fetch_and_parse<WhoAmI>(
g_endpoint_whoami,
[](const simdjson::dom::element& doc, WhoAmI& out) {
out.master_id = static_cast<unsigned int>(doc["master_id"].get_uint64());
}
);
}
std::pair<Header, Items> ApiNap::items_list() {
@ -99,4 +100,23 @@ std::pair<Header, Shops> ApiNap::market_list() {
std::pair<Header, Creators> ApiNap::fame_list() {
}
template <typename T, typename F>
std::pair<Header, T> ApiNap::fetch_and_parse (const char* endpoint, F&& data_fill) {
auto resp = m_qrest.fetch(m_prefix + endpoint);
T dataret;
{
std::unique_lock lock(m_json_mutex);
simdjson::dom::element doc = m_json.parse(
reinterpret_cast<const uint8_t*>(resp.body.data()),
resp.body.size()
);
fill_base_json(doc, dataret);
data_fill(doc, dataret);
}
return {to_header(resp), std::move(dataret)};
}
} //namespace oro

View file

@ -20,6 +20,7 @@
#include "oro/api.hpp"
#include "nap/quick_rest.hpp"
#include <mutex>
#include <utility>
namespace oro {
@ -42,6 +43,9 @@ public:
virtual std::pair<Header, Creators> fame_list() override;
private:
template <typename T, typename F>
std::pair<Header, T> fetch_and_parse (const char* endpoint, F&& data_fill);
std::mutex m_json_mutex;
simdjson::dom::parser m_json;
nap::QuickRest m_qrest;