61 lines
1.4 KiB
Rust
61 lines
1.4 KiB
Rust
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 {
|
|
true
|
|
}
|
|
}
|
|
|
|
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()))
|
|
}
|
|
}
|