session.rs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. use uuid::Uuid;
  2. use chrono::{DateTime, Utc};
  3. use sqlx::{PgPool, FromRow};
  4. use serde::Serialize;
  5. use crate::http_error::HttpError;
  6. #[derive(Serialize, FromRow)]
  7. pub struct Session {
  8. pub id: Uuid,
  9. pub game_id: Uuid,
  10. pub summary: Option<String>,
  11. pub started_at: DateTime<Utc>,
  12. pub ended_at: Option<DateTime<Utc>>,
  13. }
  14. impl Session {
  15. pub fn new(game_id: Uuid) -> Self {
  16. Self {
  17. id: Uuid::now_v7(),
  18. game_id: game_id,
  19. summary: None,
  20. started_at: Utc::now(),
  21. ended_at: None
  22. }
  23. }
  24. pub async fn insert(&self, db: &PgPool) -> Result<(), HttpError> {
  25. sqlx::query(
  26. "INSERT INTO sessions(id, game_id, summary, started_at, ended_at)
  27. VALUES($1, $2, $3, $4, $5)"
  28. )
  29. .bind(&self.id)
  30. .bind(&self.game_id)
  31. .bind(&self.summary)
  32. .bind(&self.started_at)
  33. .bind(&self.ended_at)
  34. .execute(db)
  35. .await?;
  36. Ok(())
  37. }
  38. }