Mantis App v0.1.13
Loading...
Searching...
No Matches
mantis::Context Class Reference

#include <http.h>

Public Member Functions

 Context ()=default
 
void dump ()
 Convenience method for dumping context data for debugging.
 
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_or (const std::string &key, T default_value)
 Get context value given the key.
 

Detailed Description

The Context 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.

// 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
std::optional key = ctx.get<std::string>("key");
Definition http.h:59
std::optional< T * > get(const std::string &key)
Get context value given the key.
Definition http.h:91
void set(const std::string &key, T value)
Store a key-value data in the context.
Definition http.h:78

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.

Constructor & Destructor Documentation

◆ Context()

mantis::Context::Context ( )
default

Member Function Documentation

◆ dump()

void mantis::Context::dump ( )

Convenience method for dumping context data for debugging.

◆ get()

template<typename T >
std::optional< T * > mantis::Context::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_or()

template<typename T >
T & mantis::Context::get_or ( const std::string &  key,
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

◆ set()

template<typename T >
void mantis::Context::set ( const std::string &  key,
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: