From 2e0c0a8b986001db5c135f2596c29524ff6c2ef6 Mon Sep 17 00:00:00 2001 From: Amber Ehrlich Date: Fri, 6 Oct 2023 18:43:42 -0400 Subject: [PATCH] build: refactor json.h out of include from discordevents.h --- include/dpp/discordevents.h | 22 +++++++++++++++++++++- src/dpp/discordevents.cpp | 9 +++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/include/dpp/discordevents.h b/include/dpp/discordevents.h index 6b4285f689..1f7c5d2e25 100644 --- a/include/dpp/discordevents.h +++ b/include/dpp/discordevents.h @@ -22,7 +22,6 @@ #include #include -#include #include namespace dpp { @@ -48,6 +47,27 @@ void DPP_EXPORT set_snowflake_not_null(const nlohmann::json* j, const char *keyn */ void DPP_EXPORT set_snowflake_array_not_null(const nlohmann::json* j, const char *keyname, std::vector &v); +/** + * @brief Applies a function to each element of a json array. + * @param j nlohmann::json instance to retrieve value from + * @param key key name to check for the values + * @param fn function to apply to each element + */ +void DPP_EXPORT for_each_json(const nlohmann::json* parent, std::string_view key, std::function fn); + +/** @brief Sets an array of objects from a json field value, if defined, else does nothing + * @tparam T The class of which the array consists of. Must be derived from dpp::json_interface + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for the values + * @param v Value to change + */ +template void set_object_array_not_null(const nlohmann::json* j, std::string_view key, std::vector& v) { + v.clear(); + for_each_json(j, key, [&v](const json& elem) { + v.push_back(T{}.fill_from_json(elem)); + }); +} + /** @brief Sets an array of objects from a json field value, if defined, else does nothing * @tparam T The class of which the array consists of. Must be derived from dpp::json_interface * @param j nlohmann::json instance to retrieve value from diff --git a/src/dpp/discordevents.cpp b/src/dpp/discordevents.cpp index 6454a7d1a3..be84176beb 100644 --- a/src/dpp/discordevents.cpp +++ b/src/dpp/discordevents.cpp @@ -100,6 +100,15 @@ void set_snowflake_array_not_null(const json* j, const char *keyname, std::vecto } } +void for_each_json(const nlohmann::json* parent, const char* key, std::function fn) { + auto it = parent->find(key); + if (it == parent->end() || it->is_null()) { + return; + } + for (const nlohmann::json &elem : *parent) { + fn(&elem); + } +} std::string string_not_null(const json* j, const char *keyname) { /* Returns empty string if the value is not a string, or is null or not defined */