diff options
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/mod.rs | 11 | ||||
| -rw-r--r-- | src/db/story.rs | 39 |
2 files changed, 47 insertions, 3 deletions
diff --git a/src/db/mod.rs b/src/db/mod.rs index 2f2aaeb..1d64ed8 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -13,8 +13,17 @@ pub mod tool; pub mod tooltag; #[async_trait] -pub trait DatabaseHandler { +pub trait ProductDatabaseHandler { async fn get_all(pool: SqlitePool) -> Result<Vec<Self>, AppError> where Self: Sized; + + async fn post( + &self, + pool: &SqlitePool, + name: String, + description: String, + ) -> Result<Self, AppError> + where + Self: Sized; } diff --git a/src/db/story.rs b/src/db/story.rs index 7bc5577..5acc818 100644 --- a/src/db/story.rs +++ b/src/db/story.rs @@ -2,8 +2,10 @@ use axum::async_trait; use sqlx::SqlitePool; use crate::error::AppError; +use crate::db::product::Product; + +use super::ProductDatabaseHandler; -use super::DatabaseHandler; #[derive(Debug, serde::Serialize, sqlx::FromRow)] pub struct Story { @@ -15,7 +17,7 @@ pub struct Story { } #[async_trait] -impl DatabaseHandler for Story { +impl ProductDatabaseHandler for Story { async fn get_all(pool: SqlitePool) -> Result<Vec<Self>, AppError> where Self: Sized, @@ -24,4 +26,37 @@ impl DatabaseHandler for Story { .fetch_all(&pool) .await?) } + + async fn post(&self, pool: &SqlitePool, name: String, description: String) -> Result<Self, AppError> + where + Self: Sized, + { + let time = std::time::SystemTime::now(); + let uploaddate = time.duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; + + let mut tx = pool.begin().await?; + let product = sqlx::query_as!( + Product, + "INSERT INTO product (name, description, uploaddate, updatedate) VALUES ($1, $2, $3, $4) RETURNING id, name, description, uploaddate, updatedate", + name, + description, + uploaddate, + uploaddate) + .fetch_one(&mut *tx) + .await?; + + let story = sqlx::query_as!( + Story, + "INSERT INTO story (language, pdf, epub, pid) VALUES ($1, $2, $3, $4) RETURNING id, language, pdf, epub, pid", + self.language, + self.pdf, + self.epub, + product.id) + .fetch_one(&mut *tx) + .await?; + + tx.commit().await?; + + Ok(story) + } } |
