use openlark_core::{
SDKResult,
api::{ApiRequest, ApiResponseTrait, ResponseFormat},
config::Config,
http::Transport,
req_option::RequestOption,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct DepartmentCreateRequestBuilder {
config: Config,
name: String,
parent_id: Option<String>,
leader_user_id: Option<String>,
}
impl DepartmentCreateRequestBuilder {
pub fn new(config: Config, name: impl Into<String>) -> Self {
Self {
config,
name: name.into(),
parent_id: None,
leader_user_id: None,
}
}
pub fn parent_id(mut self, parent_id: impl Into<String>) -> Self {
self.parent_id = Some(parent_id.into());
self
}
pub fn leader_user_id(mut self, leader_user_id: impl Into<String>) -> Self {
self.leader_user_id = Some(leader_user_id.into());
self
}
pub async fn execute(self) -> SDKResult<DepartmentCreateResponse> {
self.execute_with_options(RequestOption::default()).await
}
pub async fn execute_with_options(
self,
option: RequestOption,
) -> SDKResult<DepartmentCreateResponse> {
let url = "/open-apis/directory/v1/departments".to_string();
let request = DepartmentCreateRequest {
name: self.name,
parent_id: self.parent_id,
leader_user_id: self.leader_user_id,
};
let req: ApiRequest<DepartmentCreateResponse> =
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("创建部门", "响应数据为空"))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
struct DepartmentCreateRequest {
#[serde(rename = "name")]
name: String,
#[serde(rename = "parent_id", skip_serializing_if = "Option::is_none")]
parent_id: Option<String>,
#[serde(rename = "leader_user_id", skip_serializing_if = "Option::is_none")]
leader_user_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DepartmentCreateResponse {
#[serde(rename = "department_id")]
pub department_id: String,
#[serde(rename = "name")]
pub name: String,
#[serde(rename = "created_at")]
pub created_at: i64,
}
impl ApiResponseTrait for DepartmentCreateResponse {
fn data_format() -> ResponseFormat {
ResponseFormat::Data
}
}
#[deprecated(note = "renamed to DepartmentCreateRequestBuilder, will be removed in v1.0 (#271)")]
pub type DepartmentCreateBuilder = DepartmentCreateRequestBuilder;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder_basic() {
let config = openlark_core::config::Config::builder()
.app_id("test_app")
.app_secret("test_secret")
.build();
let request = DepartmentCreateRequestBuilder::new(config.clone(), "test".to_string())
.parent_id("test".to_string())
.leader_user_id("test".to_string());
let _ = request;
}
}