use openlark_core::{
SDKResult,
api::{ApiRequest, ApiResponseTrait, ResponseFormat},
config::Config,
http::Transport,
req_option::RequestOption,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct OqlQueryBuilder {
config: Config,
namespace: String,
oql: String,
fields: Vec<String>,
}
impl OqlQueryBuilder {
pub fn new(config: Config, namespace: impl Into<String>, oql: impl Into<String>) -> Self {
Self {
config,
namespace: namespace.into(),
oql: oql.into(),
fields: Vec::new(),
}
}
pub fn field(mut self, field: impl Into<String>) -> Self {
self.fields.push(field.into());
self
}
pub fn fields(mut self, fields: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.fields.extend(fields.into_iter().map(Into::into));
self
}
pub async fn execute(self) -> SDKResult<OqlQueryResponse> {
self.execute_with_options(RequestOption::default()).await
}
pub async fn execute_with_options(self, option: RequestOption) -> SDKResult<OqlQueryResponse> {
let url = format!(
"/open-apis/apaas/v1/applications/{}/objects/oql_query",
self.namespace
);
let request = OqlQueryRequest {
oql: self.oql,
fields: self.fields,
};
let req: ApiRequest<OqlQueryResponse> =
ApiRequest::post(&url).body(serde_json::to_value(&request)?);
let resp = Transport::request(req, &self.config, Some(option)).await?;
resp.data
.ok_or_else(|| openlark_core::error::validation_error("Operation", "响应数据为空"))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
struct OqlQueryRequest {
#[serde(rename = "oql")]
oql: String,
#[serde(rename = "fields", skip_serializing_if = "Vec::is_empty")]
fields: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OqlRecord {
#[serde(rename = "id")]
id: String,
#[serde(rename = "data")]
data: serde_json::Value,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OqlQueryResponse {
#[serde(rename = "items")]
items: Vec<OqlRecord>,
#[serde(rename = "has_more")]
has_more: bool,
}
impl ApiResponseTrait for OqlQueryResponse {
fn data_format() -> ResponseFormat {
ResponseFormat::Data
}
}
#[cfg(test)]
mod tests {
use serde_json;
#[test]
fn test_serialization_roundtrip() {
let json = r#"{"test": "value"}"#;
assert!(serde_json::from_str::<serde_json::Value>(json).is_ok());
}
#[test]
fn test_deserialization_from_json() {
let json = r#"{"field": "data"}"#;
let value: serde_json::Value = serde_json::from_str(json).expect("JSON 反序列化失败");
assert_eq!(value["field"], "data");
}
}