yang-base 0.1.0

个人使用构建后端服务器
Documentation
//! Action 请求结构
//!
//! 提供 Action 系统的请求封装,包含请求体、请求头、查询参数和路径参数。

use std::collections::HashMap;

/// Action 请求
///
/// 封装 HTTP 请求信息,用于 Action 执行
///
/// # 字段
///
/// - `body`: 请求体(JSON 格式)
/// - `headers`: 请求头
/// - `query`: 查询参数
/// - `path_params`: 路径参数
///
/// # 示例
///
/// ```rust,ignore
/// use yang_base::action::Request;
/// use serde_json::json;
/// use std::collections::HashMap;
///
/// // 创建请求
/// let mut request = Request::new(json!({
///     "username": "alice",
///     "email": "alice@example.com"
/// }));
///
/// // 添加请求头
/// request = request.header("Content-Type", "application/json");
/// request = request.header("Authorization", "Bearer token123");
///
/// // 添加查询参数
/// request = request.query("page", "1");
/// request = request.query("limit", "10");
///
/// // 添加路径参数
/// request = request.path_param("id", "123");
///
/// // 提取 Token
/// if let Some(token) = request.token() {
///     println!("Token: {}", token);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Request {
    /// 请求体(JSON)
    pub body: serde_json::Value,

    /// 请求头
    pub headers: HashMap<String, String>,

    /// 查询参数
    pub query: HashMap<String, String>,

    /// 路径参数
    pub path_params: HashMap<String, String>,
}

impl Request {
    /// 创建新请求
    ///
    /// # 参数
    ///
    /// - `body`: 请求体(JSON 格式)
    ///
    /// # 返回
    ///
    /// - 新的 Request 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({
    ///     "name": "Alice",
    ///     "age": 30
    /// }));
    /// ```
    pub fn new(body: serde_json::Value) -> Self {
        Self {
            body,
            headers: HashMap::new(),
            query: HashMap::new(),
            path_params: HashMap::new(),
        }
    }

    /// 添加请求头
    ///
    /// # 参数
    ///
    /// - `name`: 请求头名称
    /// - `value`: 请求头值
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .header("Content-Type", "application/json")
    ///     .header("Authorization", "Bearer token123");
    /// ```
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// 批量添加请求头
    ///
    /// # 参数
    ///
    /// - `headers`: 请求头映射
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut headers = HashMap::new();
    /// headers.insert("Content-Type".to_string(), "application/json".to_string());
    /// headers.insert("Authorization".to_string(), "Bearer token123".to_string());
    ///
    /// let request = Request::new(json!({}))
    ///     .headers(headers);
    /// ```
    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
        self.headers.extend(headers);
        self
    }

    /// 添加查询参数
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    /// - `value`: 参数值
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .query("page", "1")
    ///     .query("limit", "10");
    /// ```
    pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.insert(key.into(), value.into());
        self
    }

    /// 批量添加查询参数
    ///
    /// # 参数
    ///
    /// - `query`: 查询参数映射
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut query = HashMap::new();
    /// query.insert("page".to_string(), "1".to_string());
    /// query.insert("limit".to_string(), "10".to_string());
    ///
    /// let request = Request::new(json!({}))
    ///     .queries(query);
    /// ```
    pub fn queries(mut self, query: HashMap<String, String>) -> Self {
        self.query.extend(query);
        self
    }

    /// 添加路径参数
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    /// - `value`: 参数值
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .path_param("id", "123")
    ///     .path_param("action", "update");
    /// ```
    pub fn path_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.path_params.insert(key.into(), value.into());
        self
    }

    /// 批量添加路径参数
    ///
    /// # 参数
    ///
    /// - `path_params`: 路径参数映射
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut path_params = HashMap::new();
    /// path_params.insert("id".to_string(), "123".to_string());
    /// path_params.insert("action".to_string(), "update".to_string());
    ///
    /// let request = Request::new(json!({}))
    ///     .path_params(path_params);
    /// ```
    pub fn path_params(mut self, path_params: HashMap<String, String>) -> Self {
        self.path_params.extend(path_params);
        self
    }

    /// 从 Authorization 头提取 Token
    ///
    /// 支持 Bearer Token 格式:`Authorization: Bearer <token>`
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: Token 字符串
    /// - `None`: 未找到 Token 或格式不正确
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .header("Authorization", "Bearer my_secret_token");
    ///
    /// assert_eq!(request.token(), Some("my_secret_token"));
    /// ```
    pub fn token(&self) -> Option<&str> {
        self.headers
            .get("Authorization")
            .or_else(|| self.headers.get("authorization"))
            .and_then(|v| v.strip_prefix("Bearer "))
    }

    /// 获取请求头值
    ///
    /// # 参数
    ///
    /// - `name`: 请求头名称
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: 请求头值
    /// - `None`: 请求头不存在
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .header("Content-Type", "application/json");
    ///
    /// assert_eq!(request.get_header("Content-Type"), Some("application/json"));
    /// ```
    pub fn get_header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).map(|s| s.as_str())
    }

    /// 获取查询参数值
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: 参数值
    /// - `None`: 参数不存在
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .query("page", "1");
    ///
    /// assert_eq!(request.get_query("page"), Some("1"));
    /// ```
    pub fn get_query(&self, key: &str) -> Option<&str> {
        self.query.get(key).map(|s| s.as_str())
    }

    /// 获取路径参数值
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: 参数值
    /// - `None`: 参数不存在
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .path_param("id", "123");
    ///
    /// assert_eq!(request.get_path_param("id"), Some("123"));
    /// ```
    pub fn get_path_param(&self, key: &str) -> Option<&str> {
        self.path_params.get(key).map(|s| s.as_str())
    }
}

impl Default for Request {
    fn default() -> Self {
        Self::new(serde_json::Value::Null)
    }
}