baichun-framework-core 0.1.0

Core module for Baichun-Rust framework
Documentation
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// 上下文数据
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ContextData {
    /// 用户ID
    pub user_id: Option<String>,
    /// 租户ID
    pub tenant_id: Option<String>,
    /// 请求ID
    pub request_id: Option<String>,
    /// 其他数据
    pub extras: HashMap<String, String>,
}

/// 上下文
#[derive(Debug, Clone)]
pub struct Context {
    data: Arc<RwLock<ContextData>>,
}

impl Context {
    /// 创建新的上下文
    pub fn new() -> Self {
        Self {
            data: Arc::new(RwLock::new(ContextData::default())),
        }
    }

    /// 设置用户ID
    pub async fn set_user_id(&self, user_id: impl Into<String>) {
        let mut data = self.data.write().await;
        data.user_id = Some(user_id.into());
    }

    /// 获取用户ID
    pub async fn user_id(&self) -> Option<String> {
        let data = self.data.read().await;
        data.user_id.clone()
    }

    /// 设置租户ID
    pub async fn set_tenant_id(&self, tenant_id: impl Into<String>) {
        let mut data = self.data.write().await;
        data.tenant_id = Some(tenant_id.into());
    }

    /// 获取租户ID
    pub async fn tenant_id(&self) -> Option<String> {
        let data = self.data.read().await;
        data.tenant_id.clone()
    }

    /// 设置请求ID
    pub async fn set_request_id(&self, request_id: impl Into<String>) {
        let mut data = self.data.write().await;
        data.request_id = Some(request_id.into());
    }

    /// 获取请求ID
    pub async fn request_id(&self) -> Option<String> {
        let data = self.data.read().await;
        data.request_id.clone()
    }

    /// 设置额外数据
    pub async fn set_extra(&self, key: impl Into<String>, value: impl Into<String>) {
        let mut data = self.data.write().await;
        data.extras.insert(key.into(), value.into());
    }

    /// 获取额外数据
    pub async fn extra(&self, key: &str) -> Option<String> {
        let data = self.data.read().await;
        data.extras.get(key).cloned()
    }
}

impl Default for Context {
    fn default() -> Self {
        Self::new()
    }
}