use openlark_core::{error, SDKResult};
pub fn extract_response_data<T>(
response: openlark_core::api::ApiResponse<T>,
context: &str,
) -> SDKResult<T> {
response.data.ok_or_else(|| {
error::validation_error(
format!("{}响应数据为空", context),
"服务器没有返回有效的数据",
)
})
}
pub fn serialize_params<T: serde::Serialize>(
params: &T,
context: &str,
) -> SDKResult<serde_json::Value> {
serde_json::to_value(params).map_err(|e| {
error::validation_error(
format!("{}参数序列化失败", context),
format!("无法序列化请求参数: {}", e),
)
})
}
#[macro_export]
macro_rules! api_url {
($base_url:expr) => {
$base_url.to_string()
};
($base_url:expr, $($arg:expr),+) => {
format!($base_url, $($arg),+)
};
}
#[cfg(test)]
#[allow(unused_imports)]
mod tests {
use super::*;
use serde::Serialize;
#[derive(Serialize)]
struct TestParams {
name: String,
value: i32,
}
#[test]
fn test_serialize_params_success() {
let params = TestParams {
name: "test".to_string(),
value: 42,
};
let result = serialize_params(¶ms, "test");
assert!(result.is_ok());
let json = result.unwrap();
assert_eq!(json["name"], "test");
assert_eq!(json["value"], 42);
}
#[test]
fn test_api_url_macro_simple() {
let url = api_url!("/open-apis/test/v1/resource");
assert_eq!(url, "/open-apis/test/v1/resource");
}
#[test]
fn test_api_url_macro_with_args() {
let resource_id = "12345";
let url = api_url!("/open-apis/test/v1/resources/{}", resource_id);
assert!(url.contains("12345"));
}
#[test]
fn test_api_url_macro_with_multiple_args() {
let resource_id = "123";
let action = "approve";
let url = api_url!("/open-apis/test/v1/resources/{}/{}", resource_id, action);
assert!(url.contains("123"));
assert!(url.contains("approve"));
}
}