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> = api_endpoint
.to_request()
.body(serialize_params(&request_body, "创建文档")?);
Transport::request_typed(api_request, &self.config, Some(option), "创建").await
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use wiremock::MockServer;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, ResponseTemplate};
#[tokio::test]
async fn test_create_document_returns_data_on_success() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/open-apis/docx/v1/documents"))
.and(header("Authorization", "Bearer test-tenant-token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"code": 0, "msg": "success",
"data": { "document": { "document_id": "doc1", "revision_id": 1 } }
})))
.mount(&server)
.await;
let config = Config::builder()
.app_id("ci_app_id")
.app_secret("ci_app_secret")
.base_url(server.uri())
.enable_token_cache(false)
.build();
let resp = CreateDocumentRequest::new(config)
.title("测试文档")
.execute_with_options(
openlark_core::req_option::RequestOption::builder()
.tenant_access_token("test-tenant-token")
.build(),
)
.await
.expect("创建文档应成功");
assert_eq!(resp.document.document_id, "doc1");
assert_eq!(resp.document.revision_id, 1);
let received = server.received_requests().await.unwrap_or_default();
assert_eq!(received.len(), 1);
assert_eq!(received[0].url.path(), "/open-apis/docx/v1/documents");
let sent: serde_json::Value = serde_json::from_slice(&received[0].body).unwrap();
assert_eq!(sent["title"], "测试文档");
}
}