aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/filters.cpp74
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