|
| 1 | +use std::{collections::HashMap, default, sync::Arc}; |
| 2 | + |
| 3 | +use axum::extract::FromRef; |
| 4 | +use sqlx::{prelude::FromRow, PgPool}; |
| 5 | +use time::PrimitiveDateTime; |
| 6 | +use tokio::sync::Mutex; |
| 7 | +use uuid::Uuid; |
| 8 | + |
| 9 | +use super::{error::Error}; |
| 10 | + |
| 11 | +struct Session { |
| 12 | + current_people_listening: i32, |
| 13 | + current_people_playing: i32, |
| 14 | + max_people_playing: i32, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Clone, FromRef)] |
| 18 | +pub struct Service { |
| 19 | + db: PgPool, |
| 20 | + sessions: Arc<Mutex<HashMap<Uuid, Session>>>, |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(FromRow)] |
| 24 | +pub struct Room { |
| 25 | + pub id: Uuid, |
| 26 | + pub name: String, |
| 27 | + pub description: Option<String>, |
| 28 | + pub owner: String, |
| 29 | + pub private: bool, |
| 30 | + pub open: bool, |
| 31 | + pub max_people_playing: i32, |
| 32 | + pub created_at: PrimitiveDateTime, |
| 33 | + pub updated_at: PrimitiveDateTime, |
| 34 | +} |
| 35 | + |
| 36 | + |
| 37 | +impl Service { |
| 38 | + pub fn new(db: PgPool) -> Self { |
| 39 | + Self { |
| 40 | + db, |
| 41 | + sessions: Arc::new(Mutex::new(HashMap::new())), |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// crud operations |
| 47 | +impl Service { |
| 48 | + pub async fn create( |
| 49 | + &self, |
| 50 | + owner: String, |
| 51 | + name: String, |
| 52 | + description: Option<String>, |
| 53 | + private: bool, |
| 54 | + open: bool, |
| 55 | + max_people_playing: i32, |
| 56 | + ) -> Result<Room, Error> { |
| 57 | + let id = Uuid::new_v4(); |
| 58 | + let room = sqlx::query_as!( |
| 59 | + Room, |
| 60 | + r#"INSERT INTO rooms (id, owner, name, description, private, open, max_people_playing) |
| 61 | + VALUES ($1, $2, $3, $4, $5, $6, $7) |
| 62 | + RETURNING * |
| 63 | + "#, |
| 64 | + id, |
| 65 | + owner, |
| 66 | + name, |
| 67 | + description, |
| 68 | + private, |
| 69 | + open, |
| 70 | + max_people_playing |
| 71 | + ) |
| 72 | + .fetch_one(&self.db) |
| 73 | + .await?; |
| 74 | + |
| 75 | + self.sessions.lock().await.insert( |
| 76 | + id, |
| 77 | + Session { |
| 78 | + current_people_playing: 0, |
| 79 | + current_people_listening: 0, |
| 80 | + max_people_playing, |
| 81 | + }, |
| 82 | + ); |
| 83 | + |
| 84 | + Ok(room) |
| 85 | + } |
| 86 | + |
| 87 | + pub async fn get_by_id(&self, id: Uuid) -> Result<Option<Room>, Error> { |
| 88 | + let room = sqlx::query_as!(Room, "SELECT * FROM rooms WHERE id = $1", id) |
| 89 | + .fetch_optional(&self.db) |
| 90 | + .await?; |
| 91 | + |
| 92 | + Ok(room) |
| 93 | + } |
| 94 | + |
| 95 | + pub async fn delete(&self, id: Uuid) -> Result<(), Error> { |
| 96 | + sqlx::query!(r#"DELETE FROM rooms WHERE id = $1"#, id) |
| 97 | + .execute(&self.db) |
| 98 | + .await?; |
| 99 | + |
| 100 | + Ok(()) |
| 101 | + } |
| 102 | +} |
0 commit comments