From 2aaf500b66edb8e43a54ce64499bffb440dc6905 Mon Sep 17 00:00:00 2001 From: King_DuckZ Date: Thu, 3 Sep 2020 23:04:41 +0100 Subject: [PATCH] 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. --- src/oro/api_nap.cpp | 52 +++++++++++++++++++++++++------------ src/oro/private/api_nap.hpp | 4 +++ 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/src/oro/api_nap.cpp b/src/oro/api_nap.cpp index 25ed725..87d05a0 100644 --- a/src/oro/api_nap.cpp +++ b/src/oro/api_nap.cpp @@ -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(doc["version"].get_int64()); +} + } //unnamed namespace ApiNap::ApiNap ( @@ -66,25 +71,21 @@ ApiNap::ApiNap ( ApiNap::~ApiNap() noexcept = default; std::pair 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(resp.body.data()), - resp.body.size() - ); - - dataret.message = doc["message"]; - dataret.generation_timestamp = std::string(doc["generation_timestamp"]); - dataret.version = static_cast(int64_t(doc["version"])); - } - - return {to_header(resp), std::move(dataret)}; + return fetch_and_parse( + g_endpoint_ping, + [](const simdjson::dom::element& doc, Ping& out) { + out.message = doc["message"]; + } + ); } std::pair ApiNap::who_am_i() { + return fetch_and_parse( + g_endpoint_whoami, + [](const simdjson::dom::element& doc, WhoAmI& out) { + out.master_id = static_cast(doc["master_id"].get_uint64()); + } + ); } std::pair ApiNap::items_list() { @@ -99,4 +100,23 @@ std::pair ApiNap::market_list() { std::pair ApiNap::fame_list() { } +template +std::pair 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(resp.body.data()), + resp.body.size() + ); + + fill_base_json(doc, dataret); + data_fill(doc, dataret); + } + + return {to_header(resp), std::move(dataret)}; +} + } //namespace oro diff --git a/src/oro/private/api_nap.hpp b/src/oro/private/api_nap.hpp index 935429f..c855eee 100644 --- a/src/oro/private/api_nap.hpp +++ b/src/oro/private/api_nap.hpp @@ -20,6 +20,7 @@ #include "oro/api.hpp" #include "nap/quick_rest.hpp" #include +#include namespace oro { @@ -42,6 +43,9 @@ public: virtual std::pair fame_list() override; private: + template + std::pair fetch_and_parse (const char* endpoint, F&& data_fill); + std::mutex m_json_mutex; simdjson::dom::parser m_json; nap::QuickRest m_qrest;