#include <context_store.h>
The ContextStore class provides a means to set/get a key-value data that can be shared uniquely between middlewares and the handler functions. This allows sending data down the chain from the first to the last handler.
For instance, the auth middleware will inject user id and subsequent middlewares can retrieve it as needed.
ctx.set<std::string>(
"key",
"Value");
ctx.set<
int>(
"id", 967567);
ctx.set<
bool>(
"verified",
true);
req.set(
"key", 5
") // INT/DOUBLE/FLOATS ...
req.set("key2", { a: 5, b: 7}) // Objects/JSON
req.set("valid", true) // BOOLs
void set(const std::string &key, T value)
Store a key-value data in the context.
Definition context_store.h:81
The value returned from the get() is a std::optional, meaning a std::nullopt if the key was not found.
std::optional
key =
ctx.get<std::string>(
"key");
if(
key.has_value()) { .... }
Additionally, we have a
- See also
- get_or() method that takes in a key and a default value if the key is missing. This unlike
-
get() method, returns a
T& instead of T* depending on the usage needs.
◆ ContextStore()
| mb::ContextStore::ContextStore |
( |
| ) |
|
|
default |
◆ dump()
| void mb::ContextStore::dump |
( |
| ) |
|
Convenience method for dumping context data for debugging.
◆ get()
| std::optional< T * > mb::ContextStore::get |
( |
const std::string & |
key | ) |
|
|
inline |
Get context value given the key.
- Template Parameters
-
- Parameters
-
- Returns
- Value wrapped in a std::optional
◆ getOr()
| T & mb::ContextStore::getOr |
( |
const std::string & |
key, |
|
|
T |
default_value |
|
) |
| |
|
inline |
Get context value given the key.
- Template Parameters
-
- Parameters
-
| key | Value key |
| default_value | Default value if key is missing |
- Returns
- Value or default value
◆ hasKey()
| bool mb::ContextStore::hasKey |
( |
const std::string & |
key | ) |
const |
- Parameters
-
| key | Key to check in context store |
- Returns
true if key exists, else, false
◆ set()
template<typename T >
| void mb::ContextStore::set |
( |
const std::string & |
key, |
|
|
T |
value |
|
) |
| |
|
inline |
Store a key-value data in the context.
- Template Parameters
-
- Parameters
-
| key | Value key |
| value | Value to be stored |
The documentation for this class was generated from the following files: