summaryrefslogtreecommitdiff
path: root/src/db
diff options
context:
space:
mode:
authorWriterV2 <primary-v2@protonmail.com>2024-10-30 18:16:07 +0100
committerWriterV2 <primary-v2@protonmail.com>2024-10-30 18:16:07 +0100
commit6092e37e3a8e890cbe9d13305bcaf67daf410d93 (patch)
tree7d7e65972ac88eeb4504ab92b87b3ceeaca2584f /src/db
parent61f784a5fb437489d5dd3f629618d49279ff15a5 (diff)
Feat: Add product db handler method to post record + implement for story
Diffstat (limited to 'src/db')
-rw-r--r--src/db/mod.rs11
-rw-r--r--src/db/story.rs39
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)
+ }
}