use openlark_core::{
SDKResult,
api::{ApiRequest, ApiResponseTrait, ResponseFormat},
config::Config,
http::Transport,
req_option::RequestOption,
validate_required,
};
use serde::{Deserialize, Serialize};
use crate::common::api_endpoints::BitableApiV1;
#[derive(Debug, Clone)]
pub struct CopyDashboardRequest {
config: Config,
app_token: String,
block_id: String,
name: String,
}
impl CopyDashboardRequest {
pub fn new(config: Config) -> Self {
Self {
config,
app_token: String::new(),
block_id: String::new(),
name: String::new(),
}
}
pub fn app_token(mut self, app_token: impl Into<String>) -> Self {
self.app_token = app_token.into();
self
}
pub fn block_id(mut self, block_id: impl Into<String>) -> Self {
self.block_id = block_id.into();
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
pub async fn execute(self) -> SDKResult<CopyDashboardResponse> {
self.execute_with_options(RequestOption::default()).await
}
pub async fn execute_with_options(
self,
option: RequestOption,
) -> SDKResult<CopyDashboardResponse> {
validate_required!(self.app_token, "app_token 不能为空");
validate_required!(self.block_id, "block_id 不能为空");
validate_required!(self.name, "name 不能为空");
let api_endpoint = BitableApiV1::DashboardCopy(self.app_token, self.block_id);
let api_request: ApiRequest<CopyDashboardResponse> =
api_endpoint
.to_request()
.body(serde_json::to_vec(&CopyDashboardRequestBody {
name: self.name,
})?);
let response = Transport::request(api_request, &self.config, Some(option)).await?;
response
.data
.ok_or_else(|| openlark_core::error::validation_error("response", "响应数据为空"))
}
}
#[derive(Debug, Serialize)]
struct CopyDashboardRequestBody {
name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CopyDashboardResponse {
pub block_id: String,
pub name: String,
}
impl ApiResponseTrait for CopyDashboardResponse {
fn data_format() -> ResponseFormat {
ResponseFormat::Data
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use wiremock::MockServer;
use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};
#[tokio::test]
async fn test_copy_dashboard_returns_data_on_success() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(
"/open-apis/bitable/v1/apps/app001/dashboards/blk001/copy",
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"code": 0, "msg": "success", "data": { "block_id": "blk001", "name": "仪表盘" }
})))
.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();
CopyDashboardRequest::new(config)
.app_token("app001")
.block_id("blk001")
.name("副本")
.execute()
.await
.expect("复制仪表盘应成功");
let received = server.received_requests().await.unwrap_or_default();
assert_eq!(received.len(), 1);
assert_eq!(
received[0].url.path(),
"/open-apis/bitable/v1/apps/app001/dashboards/blk001/copy"
);
}
}