Update to more generic db models
Some checks failed
Build Crate / build (push) Has been cancelled

Also integrated entities into codebase
This commit is contained in:
2024-08-18 03:26:12 -04:00
parent 5d28013f30
commit 528682d9b1
24 changed files with 314 additions and 419 deletions

19
src/auth.rs Normal file
View File

@@ -0,0 +1,19 @@
use crate::user;
use axum_login::{AuthUser, AuthnBackend, UserId};
use serde::{Deserialize, Serialize};
// References
// https://github.com/maxcountryman/axum-login/tree/main/examples/sqlite/src
// https://framesurge.sh/perseus/en-US/docs/0.4.x/state/intro
impl AuthUser for user::Model {
type Id = i32;
fn id(&self) -> Self::Id {
self.id
}
fn session_auth_hash(&self) -> &[u8] {
self.password.as_bytes()
}
}

View File

@@ -1,5 +0,0 @@
pub mod pool_match;
pub mod user;
#[cfg(engine)]
pub mod store;

View File

@@ -1,74 +0,0 @@
use crate::data::user::PlayerId;
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
pub type MatchId = u32;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum MatchType {
Standard8Ball,
Standard9Ball,
CutThroat,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MatchData {
pub type_: MatchType,
pub winners: Vec<PlayerId>,
pub losers: Vec<PlayerId>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PoolMatch {
pub id: MatchId,
pub data: MatchData,
#[serde(with = "ts_seconds")]
pub time: DateTime<Utc>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PoolMatchList {
pub pool_matches: Vec<PoolMatch>,
pub max_id: MatchId,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct UserList{
pub users: Vec<String>,
}
impl PoolMatch {
pub fn new(data: MatchData, time: DateTime<Utc>) -> PoolMatch {
PoolMatch { id: 0, data, time }
}
}
impl PoolMatchList {
pub fn new() -> PoolMatchList {
PoolMatchList {
pool_matches: vec![],
max_id: 0,
}
}
pub fn add_pool_match(&mut self, mut pool_match: PoolMatch) {
pool_match.id = self.max_id + 1;
self.max_id += 1;
self.pool_matches.push(pool_match);
}
}
impl UserList {
pub fn new() -> UserList {
UserList {
users: vec![],
}
}
pub fn add_user(&mut self, user: String) -> usize {
let user_id = self.users.len();
self.users.push(user);
user_id
}
}

View File

@@ -1,37 +0,0 @@
// (Server only) In-memory data storage and persistent storage
use crate::data::pool_match::PoolMatchList;
use crate::data::pool_match::UserList;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::{fs, path::Path, sync::Mutex};
#[derive(Serialize, Deserialize, Clone)]
pub struct Store {
pub matches: PoolMatchList,
pub users: UserList,
}
impl Store {
fn new() -> Store {
fs::create_dir_all("data").unwrap();
match Path::new("data/store.json").exists() {
false => Store {
matches: PoolMatchList::new(),
users: UserList::new(),
},
true => {
let contents = fs::read_to_string("data/store.json").unwrap();
serde_json::from_str(&contents).unwrap()
}
}
}
// TODO -> Store data
#[allow(dead_code)]
pub fn write(&self) {
let contents = serde_json::to_string(&self).unwrap();
fs::write("data/store.json", contents).unwrap();
}
}
pub static DATA: Lazy<Mutex<Store>> = Lazy::new(|| Mutex::new(Store::new()));

View File

@@ -1,38 +0,0 @@
use axum_login::{AuthUser, AuthnBackend, UserId};
use serde::{Deserialize, Serialize};
pub type PlayerId = u32;
// References
// https://github.com/maxcountryman/axum-login/tree/main/examples/sqlite/src
// https://framesurge.sh/perseus/en-US/docs/0.4.x/state/intro
#[derive(Clone, Serialize, Deserialize)]
pub struct User {
id: u64,
pub username: String,
password: String,
}
// Override debug to prevent logging password hash
impl std::fmt::Debug for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("User")
.field("id", &self.id)
.field("username", &self.username)
.field("password", &"[hidden]")
.finish()
}
}
impl AuthUser for User {
type Id = u64;
fn id(&self) -> Self::Id {
self.id
}
fn session_auth_hash(&self) -> &[u8] {
self.password.as_bytes()
}
}

37
src/entity/game.rs Normal file
View File

@@ -0,0 +1,37 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use super::sea_orm_active_enums::GameType;
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "game")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub time: DateTimeWithTimeZone,
pub game_type: Option<GameType>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::game_to_team_result::Entity")]
GameToTeamResult,
}
impl Related<super::game_to_team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::GameToTeamResult.def()
}
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
super::game_to_team_result::Relation::TeamResult.def()
}
fn via() -> Option<RelationDef> {
Some(super::game_to_team_result::Relation::Game.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,47 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "game_to_team_result")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub game_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub team_result_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::game::Entity",
from = "Column::GameId",
to = "super::game::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
Game,
#[sea_orm(
belongs_to = "super::team_result::Entity",
from = "Column::TeamResultId",
to = "super::team_result::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
TeamResult,
}
impl Related<super::game::Entity> for Entity {
fn to() -> RelationDef {
Relation::Game.def()
}
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResult.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

10
src/entity/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub mod prelude;
pub mod game;
pub mod game_to_team_result;
pub mod sea_orm_active_enums;
pub mod team_result;
pub mod team_result_to_user;
pub mod user;

7
src/entity/prelude.rs Normal file
View File

@@ -0,0 +1,7 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub use super::game::Entity as Game;
pub use super::game_to_team_result::Entity as GameToTeamResult;
pub use super::team_result::Entity as TeamResult;
pub use super::team_result_to_user::Entity as TeamResultToUser;
pub use super::user::Entity as User;

View File

@@ -0,0 +1,15 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "game_type")]
pub enum GameType {
#[sea_orm(string_value = "PickleBall")]
PickleBall,
#[sea_orm(string_value = "Pool")]
Pool,
#[sea_orm(string_value = "TableTennis")]
TableTennis,
}

53
src/entity/team_result.rs Normal file
View File

@@ -0,0 +1,53 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "team_result")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub place: i32,
pub score: Option<i32>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::game_to_team_result::Entity")]
GameToTeamResult,
#[sea_orm(has_many = "super::team_result_to_user::Entity")]
TeamResultToUser,
}
impl Related<super::game_to_team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::GameToTeamResult.def()
}
}
impl Related<super::team_result_to_user::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResultToUser.def()
}
}
impl Related<super::game::Entity> for Entity {
fn to() -> RelationDef {
super::game_to_team_result::Relation::Game.def()
}
fn via() -> Option<RelationDef> {
Some(super::game_to_team_result::Relation::TeamResult.def().rev())
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
super::team_result_to_user::Relation::User.def()
}
fn via() -> Option<RelationDef> {
Some(super::team_result_to_user::Relation::TeamResult.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,47 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "team_result_to_user")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub team_result_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::team_result::Entity",
from = "Column::TeamResultId",
to = "super::team_result::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
TeamResult,
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::UserId",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
User,
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResult.def()
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

42
src/entity/user.rs Normal file
View File

@@ -0,0 +1,42 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub username: String,
pub password: String,
pub salt: String,
pub creation_time: DateTimeWithTimeZone,
pub last_active_time: DateTimeWithTimeZone,
pub is_admin: bool,
pub email: Option<String>,
pub avatar: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::team_result_to_user::Entity")]
TeamResultToUser,
}
impl Related<super::team_result_to_user::Entity> for Entity {
fn to() -> RelationDef {
Relation::TeamResultToUser.def()
}
}
impl Related<super::team_result::Entity> for Entity {
fn to() -> RelationDef {
super::team_result_to_user::Relation::TeamResult.def()
}
fn via() -> Option<RelationDef> {
Some(super::team_result_to_user::Relation::User.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -1,6 +1,6 @@
mod components;
mod data;
mod endpoints;
mod entity;
mod error_views;
#[cfg(engine)]
mod server;

View File

@@ -1,52 +1,16 @@
// (Server only) Routes
use crate::{
data::{
pool_match::{PoolMatch, PoolMatchList, UserList},
store::DATA,
},
endpoints::MATCH,
endpoints::USER,
};
use crate::{endpoints::USER, entity::user};
use axum::{
extract::Json,
routing::{post, Router},
};
use std::thread;
pub fn register_routes(app: Router) -> Router {
let app = app.route(MATCH, post(post_match));
let app = app.route(USER, post(post_user));
app
}
async fn post_match(Json(pool_match): Json<PoolMatch>) -> Json<PoolMatchList> {
async fn post_user(user: String) -> Json<user::Model> {
// Update the store with the new match
let matches = thread::spawn(move || {
// Get the store
let mut data = DATA.lock().unwrap();
(*data).matches.add_pool_match(pool_match);
println!("{:?}", (*data).matches.pool_matches);
(*data).matches.clone()
})
.join()
.unwrap();
Json(matches)
todo!()
}
async fn post_user(user: String) -> Json<UserList> {
// Update the store with the new match
let users = thread::spawn(move || {
// Get the store
let mut data = DATA.lock().unwrap();
let user_id = (*data).users.add_user(user);
println!("Added new user id: {}\nAll users: {:?}", user_id, (*data).users);
(*data).users.clone()
})
.join()
.unwrap();
Json(users)
}

View File

@@ -1,5 +1,4 @@
use crate::data::pool_match::MatchType;
use crate::{components::layout::Layout, data::pool_match::MatchData};
use crate::components::layout::Layout;
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
@@ -7,7 +6,6 @@ use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::data::pool_match::{PoolMatch, PoolMatchList, UserList};
use crate::templates::global_state::AppStateRx;
use crate::endpoints::{MATCH, USER};
use crate::templates::get_api_path;
@@ -29,28 +27,7 @@ fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStat
#[cfg(client)]
{
// state.winner.get().as_ref().clone()
spawn_local_scoped(cx, async move {
let new_match = PoolMatch::new(
MatchData {
type_: MatchType::Standard8Ball,
winners: vec![1],
losers: vec![2, 3, 4],
},
Utc::now(),
);
let client = reqwest::Client::new();
let new_matches = client
.post(get_api_path(MATCH).as_str())
.json(&new_match)
.send()
.await
.unwrap()
.json::<PoolMatchList>()
.await
.unwrap();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.matches.set(new_matches);
})
spawn_local_scoped(cx, async move {})
}
};
@@ -58,20 +35,7 @@ fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStat
#[cfg(client)]
{
// state.winner.get().as_ref().clone()
spawn_local_scoped(cx, async move {
let client = reqwest::Client::new();
let new_users = client
.post(get_api_path(USER).as_str())
.body(state.new_user.get().as_ref().clone())
.send()
.await
.unwrap()
.json::<UserList>()
.await
.unwrap();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.users.set(new_users);
})
spawn_local_scoped(cx, async move {})
}
};

View File

@@ -1,8 +1,5 @@
// Not a page, global state that is shared between all pages
use crate::data::pool_match::PoolMatchList;
use crate::data::pool_match::UserList;
use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize};
@@ -10,16 +7,12 @@ cfg_if::cfg_if! {
if #[cfg(engine)] {
use std::thread;
use std::ops::Deref;
use crate::data::store::DATA;
}
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AppStateRx")]
pub struct AppState {
pub matches: PoolMatchList,
pub users: UserList,
}
pub struct AppState {}
pub fn get_global_state_creator() -> GlobalStateCreator {
GlobalStateCreator::new()
@@ -29,15 +22,7 @@ pub fn get_global_state_creator() -> GlobalStateCreator {
#[engine_only_fn]
fn get_state() -> AppState {
let matches = thread::spawn(move || DATA.lock().unwrap().deref().matches.clone())
.join()
.unwrap();
let users = thread::spawn(move || DATA.lock().unwrap().deref().users.clone())
.join()
.unwrap();
AppState { matches, users }
AppState {}
}
#[engine_only_fn]

View File

@@ -1,22 +1,13 @@
use crate::{components::layout::Layout, templates::global_state::AppStateRx, data::user::PlayerId};
use crate::{components::layout::Layout, templates::global_state::AppStateRx};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use crate::data::pool_match::PoolMatch;
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {}
fn format_list_or_single(to_format: &Vec<PlayerId>) -> String{
match to_format.len() {
1 => to_format[0].to_string(),
_ => format!("{:?}", to_format),
}
}
fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
@@ -24,24 +15,7 @@ fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageSta
Layout(title = "Overall Leaderboard") {
ul {
(View::new_fragment(
global_state.matches.get()
.pool_matches
.iter()
.rev()
.map(|item: &PoolMatch| {
let game = item.clone();
view! { cx,
li (class = "text-blue-700", id = "ha",) {
(game.id)
(" ")
(format_list_or_single(&game.data.winners))
(" ")
(format_list_or_single(&game.data.losers))
}
}
})
.collect(),
vec![],
))
}
}