Skip to content

Commit

Permalink
build: refactor json.h out of include from discordevents.h
Browse files Browse the repository at this point in the history
  • Loading branch information
Mishura4 committed Oct 6, 2023
1 parent 545e7ff commit 2e0c0a8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
22 changes: 21 additions & 1 deletion include/dpp/discordevents.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

#include <dpp/export.h>
#include <dpp/json_fwd.h>
#include <dpp/json.h>
#include <dpp/json_interface.h>

namespace dpp {
Expand All @@ -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<class snowflake> &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<void(const nlohmann::json*)> 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<class T> void set_object_array_not_null(const nlohmann::json* j, std::string_view key, std::vector<T>& 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
Expand Down
9 changes: 9 additions & 0 deletions src/dpp/discordevents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<void(const nlohmann::json*)> 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 */
Expand Down

0 comments on commit 2e0c0a8

Please sign in to comment.