fish_lib/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//! # Fish Lib
//!
//! A library for fish-based games.
//!
//! ## Getting Started
//!
//! The main entry point is [`crate::game::Game`]. That's where you will find the public API to the game and storage logic.
//!
//! ```rust
//! use fish_lib::game::prelude::*;
//! use fish_lib::setup_test;
//! setup_test();
//!
//! // Example of basic usage, registering a user
//! let user = Game::register_user(1337).unwrap();
//!
//! // Re-find registered user
//! let found_user = Game::get_user(1337).unwrap();
//!
//! assert_eq!(user, found_user);
//! ```
//!
//! ## Core Modules
//!
//! - [`game`] - The primary module containing all game functionality
//! - [`config`] - Configuration types
//! - [`data`] - Supporting data structures

use crate::config::Config;
use crate::database::Database;
use crate::game::errors::database::GameDatabaseError;
use diesel::r2d2::{ConnectionManager, PooledConnection};
use diesel::PgConnection;
use lazy_static::lazy_static;
use std::path::Path;
use std::sync::{Arc, RwLock};

pub mod config;
pub mod data;
pub mod database;
pub mod enums;
pub mod game;
pub mod models;
pub mod schema;
#[cfg(test)]
pub mod tests;
pub mod traits;
pub mod utils;

lazy_static! {
    static ref DB: RwLock<Database> = RwLock::new(Database::new());
}

lazy_static! {
    static ref CONFIG: RwLock<Arc<Config>> = RwLock::new(Arc::new(Config::default()));
}

pub fn connect_db(postgres_url: &str) -> Result<(), GameDatabaseError> {
    DB.write()
        .expect("Failed to get write lock on DB")
        .connect(postgres_url)?;
    Ok(())
}

pub fn get_db_connection(
) -> Result<PooledConnection<ConnectionManager<PgConnection>>, GameDatabaseError> {
    DB.read()
        .expect("Failed to get read lock on DB")
        .get_connection()
}

pub fn clear_db() -> Result<(), GameDatabaseError> {
    DB.write().expect("Failed to get write lock on DB").clear()
}

pub fn get_config() -> Arc<Config> {
    CONFIG.read().unwrap().clone()
}

pub fn set_config(new_config: Config) {
    *CONFIG.write().unwrap() = Arc::new(new_config);
}

pub fn reset_config() {
    set_config(Config::default());
}

pub fn setup_test() {
    connect_db("postgresql://admin:root@db:5432/test_db").unwrap();
    clear_db().unwrap();

    let config = Config::builder()
        .species_json_file(Path::new("./example_data/species_data.json"))
        .unwrap()
        .build();
    set_config(config);
}