Ported randoms to the DB
+ Also added commands for adding and listing randoms + fmt, clippy failing in a library...
This commit is contained in:
@@ -0,0 +1 @@
|
||||
pub mod random;
|
||||
@@ -0,0 +1,60 @@
|
||||
use crate::error::Error;
|
||||
use j_db::database::Database;
|
||||
use j_db::model::JdbModel;
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::thread_rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct RandomConfig {
|
||||
id: Option<u64>,
|
||||
pub name: String,
|
||||
pub responses: Vec<String>,
|
||||
}
|
||||
|
||||
impl JdbModel for RandomConfig {
|
||||
fn id(&self) -> Option<u64> {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn set_id(&mut self, id: u64) {
|
||||
self.id = Some(id)
|
||||
}
|
||||
|
||||
fn tree() -> String {
|
||||
"randoms".to_string()
|
||||
}
|
||||
|
||||
fn check_unique(&self, other: &Self) -> bool {
|
||||
!self.name.eq_ignore_ascii_case(&other.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl RandomConfig {
|
||||
pub fn add_random(db: &Database, name: &str, response: &str) -> Result<(), Error> {
|
||||
let mut random = match Self::get_random(db, name)? {
|
||||
None => db.insert::<RandomConfig>(Self {
|
||||
id: None,
|
||||
name: name.to_string(),
|
||||
responses: vec![],
|
||||
})?,
|
||||
Some(random) => random,
|
||||
};
|
||||
|
||||
random.responses.push(response.to_string());
|
||||
|
||||
db.insert::<RandomConfig>(random)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_random(db: &Database, name: &str) -> Result<Option<Self>, Error> {
|
||||
Ok(db
|
||||
.filter(|_, random: &RandomConfig| random.name.eq_ignore_ascii_case(name))?
|
||||
.next())
|
||||
}
|
||||
|
||||
pub fn get_response(&self) -> Result<Option<&String>, Error> {
|
||||
Ok(self.responses.choose(&mut thread_rng()))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user