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