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 GetAction {
table_config: Arc<TableConfig>,
}
impl GetAction {
pub fn new(table_config: Arc<TableConfig>) -> Self {
Self { table_config }
}
}
#[async_trait]
impl Action for GetAction {
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 query = context
.table_query()?
.where_eq(pk_field.as_str(), pk_value)?;
#[cfg(feature = "mysql")]
{
use crate::table::DynamicRow;
let row = query.fetch_optional::<DynamicRow>().await?;
match row {
None => Err(BaseError::RecordNotFound(format!(
"表 {} 中主键为 {} 的记录不存在",
self.table_config.table_name, pk_field
))),
Some(record) => ApiResponse::success(record, "获取成功"),
}
}
#[cfg(not(feature = "mysql"))]
{
let _ = query;
Err(BaseError::Unknown(
"GetAction 需要启用 mysql feature".to_string(),
))
}
}
fn name(&self) -> &str {
"get"
}
fn display_name(&self) -> &str {
"获取数据"
}
fn description(&self) -> &str {
"根据主键获取数据表中的单条记录"
}
}