Skip to main content

openlark_workflow/common/
api_utils.rs

1/// API通用工具函数
2///
3/// 提供API实现的通用工具和辅助函数,减少重复代码,提高一致性
4use openlark_core::{error, SDKResult};
5
6/// 标准化API响应数据提取
7///
8/// # 参数
9/// - `response`: API响应对象
10/// - `context`: 错误上下文描述
11///
12/// # 返回
13/// - `Ok(T)`: 成功提取的数据
14/// - `Err(SDKError)`: 包含上下文信息的错误
15pub fn extract_response_data<T>(
16    response: openlark_core::api::Response<T>,
17    context: &str,
18) -> SDKResult<T> {
19    response.data.ok_or_else(|| {
20        error::validation_error(
21            format!("{}响应数据为空", context).as_str(),
22            "服务器没有返回有效的数据",
23        )
24    })
25}
26
27/// 标准化参数序列化错误处理
28///
29/// # 参数
30/// - `params`: 要序列化的参数
31/// - `context`: 序列化上下文
32///
33/// # 返回
34/// - `Ok(serde_json::Value)`: 序列化成功
35/// - `Err(SDKError)`: 包含详细信息的序列化错误
36pub fn serialize_params<T: serde::Serialize>(
37    params: &T,
38    context: &str,
39) -> SDKResult<serde_json::Value> {
40    serde_json::to_value(params).map_err(|e| {
41        error::validation_error(
42            format!("{}参数序列化失败", context).as_str(),
43            format!("无法序列化请求参数: {}", e).as_str(),
44        )
45    })
46}
47
48/// 标准化API端点URL生成辅助宏
49///
50/// # 使用示例
51/// ```rust
52/// # fn main() {
53/// // openlark_task 模块暂未实现
54/// // use openlark_task::api_url;
55///
56/// // let task_guid = "task_guid";
57/// // let url = api_url!("/open-apis/task/v2/tasks/{}", task_guid);
58/// // assert!(url.contains(task_guid));
59/// # }
60/// ```
61#[macro_export]
62macro_rules! api_url {
63    ($base_url:expr) => {
64        $base_url.to_string()
65    };
66    ($base_url:expr, $($arg:expr),+) => {
67        format!($base_url, $($arg),+)
68    };
69}