use crate::action::{Action, ActionContext, ApiResponse};
use crate::error::BaseError;
use crate::table::{SortOrder, TableConfig};
use async_trait::async_trait;
use std::sync::Arc;
#[allow(dead_code)]
pub struct SelectAction {
table_config: Arc<TableConfig>,
}
impl SelectAction {
pub fn new(table_config: Arc<TableConfig>) -> Self {
Self { table_config }
}
}
#[async_trait]
impl Action for SelectAction {
async fn execute(&self, context: ActionContext) -> Result<ApiResponse, BaseError> {
let page: usize = context.param_optional::<i64>("page").unwrap_or(1) as usize;
let page_size: usize = context.param_optional::<i64>("page_size").unwrap_or(10) as usize;
let mut query = context.table_query()?;
if let Some(fields) = context.param_optional::<Vec<String>>("fields") {
let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
query = query.select_fields(&field_refs)?;
}
if let Some(where_conditions) = context.param_optional::<serde_json::Value>("where") {
if let Some(obj) = where_conditions.as_object() {
for (field, value) in obj {
query = query.where_eq(field.as_str(), value.clone())?;
}
}
}
if let Some(order_by) = context.param_optional::<Vec<serde_json::Value>>("order_by") {
for order in order_by {
if let Some(obj) = order.as_object() {
if let (Some(field), Some(direction)) = (obj.get("field"), obj.get("direction"))
{
let field_str = field.as_str().ok_or_else(|| {
BaseError::ParamInvalid(
"order_by".to_string(),
"field 必须是字符串".to_string(),
)
})?;
let direction_str = direction.as_str().ok_or_else(|| {
BaseError::ParamInvalid(
"order_by".to_string(),
"direction 必须是字符串".to_string(),
)
})?;
let sort_order = match direction_str.to_lowercase().as_str() {
"asc" => SortOrder::Asc,
"desc" => SortOrder::Desc,
_ => {
return Err(BaseError::ParamInvalid(
"order_by".to_string(),
"direction 必须是 'asc' 或 'desc'".to_string(),
))
}
};
query = query.order_by(field_str, sort_order)?;
}
}
}
}
let _query = query.page(page, page_size)?;
return Err(BaseError::Unknown(
"SelectAction 需要在实际使用时提供具体的数据类型实现".to_string(),
));
}
fn name(&self) -> &str {
"select"
}
fn display_name(&self) -> &str {
"查询列表"
}
fn description(&self) -> &str {
"分页查询数据表中的记录列表"
}
fn params_schema(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({
"type": "object",
"properties": {
"fields": {
"type": "array",
"items": { "type": "string" },
"description": "要查询的字段列表"
},
"where": {
"type": "object",
"description": "筛选条件"
},
"order_by": {
"type": "array",
"items": {
"type": "object",
"properties": {
"field": { "type": "string" },
"direction": { "type": "string", "enum": ["asc", "desc"] }
}
},
"description": "排序规则"
},
"page": {
"type": "integer",
"minimum": 1,
"description": "页码(默认 1)"
},
"page_size": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"description": "每页大小(默认 10)"
}
}
}))
}
}