use openlark_core::{
SDKResult,
api::{ApiRequest, ApiResponseTrait, ResponseFormat},
config::Config,
http::Transport,
};
use serde::{Deserialize, Serialize};
use crate::common::{api_endpoints::DocxApiV1, api_utils::*};
pub struct CreateDocumentRequest {
config: Config,
title: Option<String>,
folder_token: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct CreateDocumentRequestBody {
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub folder_token: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateDocumentResponse {
pub document: CreatedDocument,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreatedDocument {
pub document_id: String,
pub revision_id: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
}
impl ApiResponseTrait for CreateDocumentResponse {
fn data_format() -> ResponseFormat {
ResponseFormat::Data
}
}
impl CreateDocumentRequest {
pub fn new(config: Config) -> Self {
Self {
config,
title: None,
folder_token: None,
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn folder_token(mut self, folder_token: impl Into<String>) -> Self {
self.folder_token = Some(folder_token.into());
self
}
pub async fn execute(self) -> SDKResult<CreateDocumentResponse> {
self.execute_with_options(openlark_core::req_option::RequestOption::default())
.await
}
pub async fn execute_with_options(
self,
option: openlark_core::req_option::RequestOption,
) -> SDKResult<CreateDocumentResponse> {
let api_endpoint = DocxApiV1::DocumentCreate;
let request_body = CreateDocumentRequestBody {
title: self.title,
folder_token: self.folder_token,
};
let api_request: ApiRequest<CreateDocumentResponse> =
ApiRequest::post(&api_endpoint.to_url())
.body(serialize_params(&request_body, "创建文档")?);
let response = Transport::request(api_request, &self.config, Some(option)).await?;
extract_response_data(response, "创建")
}
}
#[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");
}
}