synthwave/src/library/event.rs

42 lines
1.1 KiB
Rust
Raw Normal View History

2024-08-16 23:25:41 +00:00
use serde::{Deserialize, Serialize};
2024-10-04 10:00:33 +00:00
use sqlx::prelude::FromRow;
2024-08-16 23:25:41 +00:00
2024-10-04 10:00:33 +00:00
use crate::{get_pg, library::user::User};
2024-08-16 23:25:41 +00:00
2024-10-04 10:00:33 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
2024-08-16 23:25:41 +00:00
pub struct Event {
2024-10-04 10:00:33 +00:00
pub id: uuid::Uuid,
2024-10-04 17:39:51 +00:00
pub time: chrono::DateTime<chrono::Utc>,
2024-08-16 23:25:41 +00:00
pub kind: EventKind,
2024-10-04 10:00:33 +00:00
pub user: String,
pub track: uuid::Uuid,
2024-08-16 23:25:41 +00:00
}
2024-10-04 10:00:33 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "event_kind", rename_all = "lowercase")]
2024-08-16 23:25:41 +00:00
pub enum EventKind {
Play,
Played,
Stop,
}
impl Event {
2024-10-04 10:00:33 +00:00
pub async fn create(kind: EventKind, user: &User, track: uuid::Uuid) -> Self {
2024-10-04 17:39:51 +00:00
sqlx::query_as("INSERT INTO events (kind, \"user\", track) VALUES ($1, $2, $3) RETURNING *")
2024-10-04 10:00:33 +00:00
.bind(kind)
.bind(&user.username)
.bind(track)
.fetch_one(get_pg!())
.await
.unwrap()
2024-08-16 23:25:41 +00:00
}
pub async fn get_latest_events_of(u: &User) -> Vec<Self> {
2024-10-04 17:39:51 +00:00
sqlx::query_as("SELECT * FROM events WHERE \"user\" = $1 ORDER BY time DESC LIMIT 300")
2024-10-04 10:00:33 +00:00
.bind(&u.username)
.fetch_all(get_pg!())
.await
.unwrap()
2024-08-16 23:25:41 +00:00
}
}