diff options
author | Michael Jurkoic <mjjurkoic@gmail.com> | 2024-03-12 09:34:51 -0500 |
---|---|---|
committer | Michael Jurkoic <mjjurkoic@gmail.com> | 2024-03-12 09:34:51 -0500 |
commit | c564313f7e97f2fd7db98c2acca187c809a40a8c (patch) | |
tree | 71a5420340b981df146c76cce0a1db9693980c4f /src | |
parent | 760d5d9adab13edc090f64437415b41b229481f8 (diff) |
Add a filters struct for relay queries
Diffstat (limited to 'src')
-rw-r--r-- | src/filters.cpp | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/src/filters.cpp b/src/filters.cpp new file mode 100644 index 0000000..78f3ce4 --- /dev/null +++ b/src/filters.cpp @@ -0,0 +1,74 @@ +#include <ctime> +#include <sstream> +#include <string> +#include <nlohmann/json.hpp> + +#include "nostr.hpp" + +using nlohmann::json; +using std::invalid_argument; +using std::stringstream; +using std::string; +using std::time; + +namespace nostr +{ +string Filters::serialize() +{ + try + { + this->validate(); + } + catch (const invalid_argument& e) + { + throw e; + } + + json j = { + {"ids", this->ids}, + {"authors", this->authors}, + {"kinds", this->kinds}, + {"since", this->since}, + {"until", this->until}, + {"limit", this->limit} + }; + + for (auto& tag : this->tags) + { + stringstream jss; + jss << "#" << tag.first; + string js = jss.str(); + + j[js] = tag.second; + } + + return j.dump(); +}; + +void Filters::validate() +{ + bool hasLimit = this->limit > 0; + if (!hasLimit) + { + throw invalid_argument("Filters::validate: The limit must be greater than 0."); + } + + bool hasUntil = this->until > 0; + if (!hasUntil) + { + this->until = time(nullptr); + } + + bool hasIds = this->ids.size() > 0; + bool hasAuthors = this->authors.size() > 0; + bool hasKinds = this->kinds.size() > 0; + bool hasTags = this->tags.size() > 0; + + bool hasFilter = hasIds || hasAuthors || hasKinds || hasTags; + + if (!hasFilter) + { + throw invalid_argument("Filters::validate: At least one filter must be set."); + } +}; +} // namespace nostr |