use serde_json::{Map, Value};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct RequestContext<'a> {
method: &'a str,
params: Option<Value>,
metadata: Map<String, Value>,
bearer_token: Option<String>,
extensions: HashMap<String, Value>,
}
impl<'a> RequestContext<'a> {
pub fn new(method: &'a str, params: Option<Value>) -> Self {
Self {
method,
params,
metadata: Map::new(),
bearer_token: None,
extensions: HashMap::new(),
}
}
pub fn method(&self) -> &str {
self.method
}
pub fn params(&self) -> Option<&Value> {
self.params.as_ref()
}
pub fn params_mut(&mut self) -> Option<&mut Value> {
self.params.as_mut()
}
pub fn metadata(&self) -> &Map<String, Value> {
&self.metadata
}
pub fn add_metadata(&mut self, key: impl Into<String>, value: Value) {
self.metadata.insert(key.into(), value);
}
pub fn bearer_token(&self) -> Option<&str> {
self.bearer_token.as_deref()
}
pub fn set_bearer_token(&mut self, token: String) {
self.bearer_token = Some(token);
}
pub fn extensions(&self) -> &HashMap<String, Value> {
&self.extensions
}
pub fn set_extension(&mut self, key: impl Into<String>, value: Value) {
self.extensions.insert(key.into(), value);
}
pub fn get_extension(&self, key: &str) -> Option<&Value> {
self.extensions.get(key)
}
pub fn take_extensions(&mut self) -> HashMap<String, Value> {
std::mem::take(&mut self.extensions)
}
}
#[derive(Debug, Default, Clone)]
pub struct SessionInjection {
state: HashMap<String, Value>,
metadata: HashMap<String, Value>,
}
impl SessionInjection {
pub fn new() -> Self {
Self::default()
}
pub fn set_state(&mut self, key: impl Into<String>, value: Value) {
self.state.insert(key.into(), value);
}
pub fn set_metadata(&mut self, key: impl Into<String>, value: Value) {
self.metadata.insert(key.into(), value);
}
pub(crate) fn state(&self) -> &HashMap<String, Value> {
&self.state
}
pub(crate) fn metadata(&self) -> &HashMap<String, Value> {
&self.metadata
}
pub fn is_empty(&self) -> bool {
self.state.is_empty() && self.metadata.is_empty()
}
}
#[derive(Debug, Clone)]
pub enum DispatcherResult {
Success(Value),
Error(String),
}
impl DispatcherResult {
pub fn is_success(&self) -> bool {
matches!(self, Self::Success(_))
}
pub fn is_error(&self) -> bool {
matches!(self, Self::Error(_))
}
pub fn success(&self) -> Option<&Value> {
match self {
Self::Success(v) => Some(v),
Self::Error(_) => None,
}
}
pub fn success_mut(&mut self) -> Option<&mut Value> {
match self {
Self::Success(v) => Some(v),
Self::Error(_) => None,
}
}
pub fn error(&self) -> Option<&str> {
match self {
Self::Success(_) => None,
Self::Error(e) => Some(e),
}
}
}