#![cfg(feature = "mysql")]
use crate::action::{ActionContext, TypedHandler};
use crate::error::BaseError;
use crate::table::TableEntity;
use async_trait::async_trait;
use serde::Serialize;
use std::collections::HashMap;
use std::marker::PhantomData;
use yang_base_derive::Action;
#[derive(Serialize, schemars::JsonSchema)]
pub struct AffectedResult {
pub affected: u64,
}
#[derive(Serialize, schemars::JsonSchema)]
pub struct InsertResult {
pub affected: u64,
pub id: u64,
}
#[derive(Action)]
#[action(
name = "add",
display_name = "新增数据",
description = "向表中插入一条记录"
)]
pub struct AddAction<T: TableEntity> {
_phantom: PhantomData<T>,
}
impl<T: TableEntity> AddAction<T> {
pub fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<T: TableEntity> Default for AddAction<T> {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl<T: TableEntity> TypedHandler for AddAction<T> {
type Input = T;
type Output = InsertResult;
async fn handle(&self, ctx: ActionContext, input: T) -> Result<InsertResult, BaseError> {
let value = serde_json::to_value(&input)
.map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
let map: HashMap<String, serde_json::Value> = match value {
serde_json::Value::Object(m) => m.into_iter().collect(),
_ => {
return Err(BaseError::ParamInvalid(
"body".into(),
"实体必须序列化为对象".into(),
))
}
};
let (affected, id) = ctx.table_query()?.insert_returning_id(map).await?;
Ok(InsertResult { affected, id })
}
}