notification (#282)
All checks were successful
CI/CD Pipeline / test (push) Successful in 8m58s
CI/CD Pipeline / deploy-staging (push) Successful in 4m18s
CI/CD Pipeline / deploy-main (push) Has been skipped

Reviewed-on: #282
This commit is contained in:
2024-03-20 16:19:12 +01:00
parent 68a1153885
commit 9d14dae4a7
12 changed files with 274 additions and 22 deletions

View File

@ -1,36 +1,78 @@
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
use std::ops::DerefMut;
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
use super::user::User;
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Notification {
pub id: i64,
pub user_id: i64,
pub message: String,
pub read_at: NaiveDateTime,
pub read_at: Option<NaiveDateTime>,
pub created_at: NaiveDateTime,
pub category: String,
pub link: Option<String>,
}
impl Notification {
//pub async fn create(db: &SqlitePool, msg: String) -> bool {
// sqlx::query!("INSERT INTO log(msg) VALUES (?)", msg,)
// .execute(db)
// .await
// .is_ok()
//}
pub async fn find_by_id(db: &SqlitePool, id: i64) -> Option<Self> {
sqlx::query_as!(Self, "SELECT * FROM notification WHERE id like ?", id)
.fetch_one(db)
.await
.ok()
}
pub async fn create_with_tx(
db: &mut Transaction<'_, Sqlite>,
user: &User,
message: &str,
category: &str,
link: Option<&str>,
) {
sqlx::query!(
"INSERT INTO notification(user_id, message, category, link) VALUES (?, ?, ?, ?)",
user.id,
message,
category,
link
)
.execute(db.deref_mut())
.await
.unwrap();
}
async fn for_user(db: &SqlitePool, user: &User) -> Vec<Self> {
pub async fn create(
db: &SqlitePool,
user: &User,
message: &str,
category: &str,
link: Option<&str>,
) {
let mut tx = db.begin().await.unwrap();
Self::create_with_tx(&mut tx, user, message, category, link).await;
tx.commit().await.unwrap();
}
pub async fn for_user(db: &SqlitePool, user: &User) -> Vec<Self> {
sqlx::query_as!(
Log,
"
SELECT id, user_id, message, read_at, category
FROM notification
WHERE user_id = {}
",
Self,
"SELECT * FROM notification WHERE user_id = ?",
user.id
)
.fetch_all(db)
.await
.unwrap()
}
pub async fn mark_read(self, db: &SqlitePool) {
sqlx::query!(
"UPDATE notification SET read_at=CURRENT_TIMESTAMP WHERE id=?",
self.id
)
.execute(db)
.await
.unwrap();
}
}