morethantext-web/src/morethantext/store.rs

94 lines
2.3 KiB
Rust

use super::{Data, Database, ErrorCode, MTTError};
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub struct Store {
data: HashMap<String, Data<Database>>,
}
impl Store {
pub fn new() -> Self {
Self {
data: HashMap::new(),
}
}
pub fn add<S>(&mut self, name: S) -> Result<(), MTTError>
where
S: Into<String>,
{
let db_name = name.into();
match self.get(&db_name) {
Some(_) => Err(MTTError::from_code(ErrorCode::DuplicateDatabase(db_name))),
None => {
self.data.insert(db_name, Data::from_data(Database::new()));
Ok(())
}
}
}
pub fn get(&self, name: &str) -> Option<&Data<Database>> {
self.data.get(name)
}
pub fn list(&self) -> Vec<String> {
Vec::new()
}
}
#[cfg(test)]
mod storage {
use super::*;
#[test]
fn create_new() {
let store = Store::new();
let expected: Vec<String> = Vec::new();
assert_eq!(store.list(), expected);
}
#[test]
fn add_db_by_str() {
let mut store = Store::new();
let name = "Melvin";
store.add(name).unwrap();
let output = store.get(name);
assert!(output.is_some(), "Get returned none.");
}
#[test]
fn add_db_by_string() {
let mut store = Store::new();
let name = "Marvin";
store.add(name.to_string()).unwrap();
let output = store.get(name);
assert!(output.is_some(), "Get returned none.");
}
#[test]
fn fail_on_duplicates() -> Result<(), MTTError> {
let mut store = Store::new();
let name = "Mickie";
store.add(name).unwrap();
match store.add(name) {
Ok(_) => Err(MTTError::new("duplicates should error")),
Err(err) => match err.code {
ErrorCode::DuplicateDatabase(db_name) => {
assert_eq!(db_name, name);
Ok(())
}
_ => Err(MTTError::new(format!("{:?} is not DuplicateDatabase", err))),
},
}
}
#[test]
fn get_bad_database() -> Result<(), MTTError> {
let store = Store::new();
match store.get("missing") {
Some(_) => Err(MTTError::new("Should have returned None.")),
None => Ok(()),
}
}
}