diff --git a/include/dpp/discordevents.h b/include/dpp/discordevents.h index 6b4285f689..d2c80c8ed1 100644 --- a/include/dpp/discordevents.h +++ b/include/dpp/discordevents.h @@ -22,7 +22,6 @@ #include #include -#include #include namespace dpp { @@ -48,21 +47,25 @@ 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(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 std::enable_if_t, T>, void> set_object_array_not_null(nlohmann::json* j, const char *keyname, std::vector &v) { +template void set_object_array_not_null(nlohmann::json* j, std::string_view key, std::vector& v) { v.clear(); - auto k = j->find(keyname); - if (k != j->end() && !k->is_null()) { - v.reserve(j->at(keyname).size()); - for (auto &obj : j->at(keyname)) { - v.emplace_back(T().fill_from_json(&obj)); - } - } + for_each_json(j, key, [&v](nlohmann::json* elem) { + v.push_back(T{}.fill_from_json(elem)); + }); } /** @brief Returns a string from a json field value, if defined, else returns an empty string. 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 */