use crate::action::{Action, ActionContext, ApiResponse};
use crate::error::BaseError;
use crate::table::TableConfig;
use async_trait::async_trait;
use std::sync::Arc;
pub struct PutAction {
table_config: Arc<TableConfig>,
}
impl PutAction {
pub fn new(table_config: Arc<TableConfig>) -> Self {
Self { table_config }
}
}
#[async_trait]
impl Action for PutAction {
async fn execute(&self, context: ActionContext) -> Result<ApiResponse, BaseError> {
let pk_field = &self.table_config.primary_key;
let pk_value: serde_json::Value = context.param(pk_field)?;
let data: serde_json::Value = context.param("data")?;
let data_obj = data.as_object().ok_or_else(|| {
BaseError::ParamInvalid("data".to_string(), "必须是对象类型".to_string())
})?;
let mut data_map = std::collections::HashMap::new();
for (k, v) in data_obj {
data_map.insert(k.clone(), v.clone());
}
let mut query = context.table_query()?;
query = query.where_eq(pk_field.as_str(), pk_value)?;
let affected = query.update(data_map).await?;
Ok(ApiResponse::success(
serde_json::json!({ "affected": affected }),
"更新成功",
)?)
}
fn name(&self) -> &str {
"put"
}
fn display_name(&self) -> &str {
"更新数据"
}
fn description(&self) -> &str {
"根据主键更新数据表中的记录"
}
fn params_schema(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({
"type": "object",
"properties": {
"data": {
"type": "object",
"description": "要更新的数据对象"
}
},
"required": ["data"]
}))
}
}