MantisBase v0.3.4
Loading...
Searching...
No Matches
context_store.h
Go to the documentation of this file.
1//
2// Created by allan on 18/10/2025.
3//
4
5#ifndef MANTISAPP_CONTEXTSTORE_H
6#define MANTISAPP_CONTEXTSTORE_H
7
8#include <nlohmann/json.hpp>
9#include "../utils/utils.h"
10
11#ifdef MANTIS_ENABLE_SCRIPTING
12#include <dukglue/dukglue.h>
13#endif
14
15namespace mb
16{
18 using json = nlohmann::json;
19
55 {
56 std::unordered_map<std::string, std::any> data;
57 std::string __class_name__ = "mb::ContextStore";
58
59 public:
60 ContextStore() = default;
64 void dump();
65
71 bool hasKey(const std::string& key) const;
72
80 template <typename T>
81 void set(const std::string& key, T value)
82 {
83 data[key] = std::move(value);
84 }
85
93 template <typename T>
94 std::optional<T*> get(const std::string& key)
95 {
96 const auto it = data.find(key);
97 if (it != data.end())
98 return std::any_cast<T>(&it->second);
99
100 return std::nullopt;
101 }
102
111 template <typename T>
112 T& getOr(const std::string& key, T default_value)
113 {
114 if (const auto it = data.find(key); it == data.end())
115 {
116 data[key] = std::move(default_value);
117 }
118 return std::any_cast<T&>(data.at(key));
119 }
120
121#ifdef MANTIS_ENABLE_SCRIPTING
122 DukValue get_duk(const std::string& key);
123
131 DukValue getOr_duk(const std::string& key, DukValue default_value);
132
139 void set_duk(const std::string& key, const DukValue& value);
140#endif
141 };
142
143} // mb
144
145#endif //MANTISAPP_CONTEXTSTORE_H
Definition context_store.h:55
bool hasKey(const std::string &key) const
Definition context_store.cpp:51
void dump()
Convenience method for dumping context data for debugging.
Definition context_store.cpp:11
T & getOr(const std::string &key, T default_value)
Get context value given the key.
Definition context_store.h:112
void set(const std::string &key, T value)
Store a key-value data in the context.
Definition context_store.h:81
ContextStore()=default
std::optional< T * > get(const std::string &key)
Get context value given the key.
Definition context_store.h:94
router.h
Definition auth.h:15
nlohmann::json json
Shorten JSON namespace.
Definition context_store.h:18