MantisBase v0.4.9
Loading...
Searching...
No Matches
mb::MbContextStore Class Reference

#include <context_store.h>

Public Member Functions

 MbContextStore ()=default
void dump ()
 Convenience method for dumping context data for debugging.
bool hasKey (const std::string &key) const
template<typename T>
void set (const std::string &key, T value)
 Store a key-value data in the context.
template<typename T>
std::optional< T * > get (const std::string &key)
 Get context value given the key.
template<typename T>
T & get (const std::string &key, T default_value)
 Get context value given the key.

Detailed Description

The MbContextStore class provides a key-value store for scripting and internal utilities. HTTP handlers should use MbRequest::set and MbRequest::get for per-request attributes (auth, etc.).

For instance, the auth middleware will inject user id and subsequent middlewares can retrieve it as needed.

// Create the object
Context ctx;
// Add values
ctx.set<std::string>("key", "Value");
ctx.set<int>("id", 967567);
ctx.set<bool>("verified", true);
// Retrieve values
// From scripting using JS
req.set("key", 5") // INT/DOUBLE/FLOATS ...
req.set("key2", { a: 5, b: 7}) // Objects/JSON
req.set("valid", true) // BOOLs
req.get("nothing", "Default Value")

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 an overload of

See also
get() that takes in a key and a default value if the key is missing. This unlike the optional-returning
get() method, returns a T& instead of T* depending on the usage needs.

Constructor & Destructor Documentation

◆ MbContextStore()

mb::MbContextStore::MbContextStore ( )
default

Member Function Documentation

◆ dump()

void mb::MbContextStore::dump ( )

Convenience method for dumping context data for debugging.

◆ get() [1/2]

template<typename T>
std::optional< T * > mb::MbContextStore::get ( const std::string & key)
inline

Get context value given the key.

Template Parameters
TValue data type
Parameters
keyValue key
Returns
Value wrapped in a std::optional

◆ get() [2/2]

template<typename T>
T & mb::MbContextStore::get ( const std::string & key,
T default_value )
inline

Get context value given the key.

Template Parameters
TValue data type
Parameters
keyValue key
default_valueDefault value if key is missing
Returns
Value or default value

◆ hasKey()

bool mb::MbContextStore::hasKey ( const std::string & key) const
Parameters
keyKey to check in context store
Returns
true if key exists, else, false

◆ set()

template<typename T>
void mb::MbContextStore::set ( const std::string & key,
T value )
inline

Store a key-value data in the context.

Template Parameters
TValue data type
Parameters
keyValue key
valueValue to be stored

The documentation for this class was generated from the following files: