From 659a2758bb1312879092e5efb83744ae96ce8631 Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Tue, 4 Apr 2023 09:59:29 -0400 Subject: [PATCH] Pulled back to use async channels. --- src/main.rs | 4 +- src/morethantext/mod.rs | 101 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 src/morethantext/mod.rs diff --git a/src/main.rs b/src/main.rs index 8fbfa36..257ef63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,7 @@ use tide::{ mod morethantext; mod settings; -use morethantext::MoreThanText; +use morethantext::{start_db, MoreThanText}; use settings::Settings; #[async_std::main] @@ -20,7 +20,7 @@ async fn main() -> tide::Result<()> { } async fn app_setup(data_dir: &str) -> tide::Server { - let db = MoreThanText::new(data_dir).await.unwrap(); + let db = start_db(data_dir).await.unwrap(); let mut app = tide::with_state(db); app.at("/").get(home); app.with( diff --git a/src/morethantext/mod.rs b/src/morethantext/mod.rs new file mode 100644 index 0000000..265b659 --- /dev/null +++ b/src/morethantext/mod.rs @@ -0,0 +1,101 @@ +use async_std::{ + channel::{unbounded, Sender}, + path::PathBuf, + task::spawn, +}; +use std::{error::Error, fmt}; + +const ENTRY: &str = "EntryPoint"; + +#[derive(Debug)] +pub struct MTTError { + msg: String, +} + +impl MTTError { + fn new(msg: S) -> Self where S: Into { + let text = msg.into(); + Self { + msg: text, + } + } +} + +impl Error for MTTError {} + +impl fmt::Display for MTTError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.msg) + } +} + +#[cfg(test)] +mod errors { + use super::*; + + #[test] + fn create_with_str() { + let msgs = ["one", "two"]; + for msg in msgs { + let err = MTTError::new(msg); + assert_eq!(err.to_string(), msg); + } + } + + #[test] + fn create_with_string() { + let msg = "three"; + let err = MTTError::new(msg.to_string()); + assert_eq!(err.to_string(), msg); + } +} + +#[derive(Clone)] +struct Store; + +#[derive(Clone)] +enum DataType { + DBMap(Store), +} + +#[derive(Clone)] +pub struct MoreThanText { + session: Vec, + channel: Sender, +} + +impl MoreThanText { + async fn get_entry(&self, id: String) { + self.channel.send(id).await.unwrap(); + } +} + +pub async fn start_db

(dir: P) -> Result +where + P: Into, +{ + let data_dir = dir.into(); + let (s, r) = unbounded(); + spawn(async move { + loop { + r.recv().await.unwrap(); + } + }); + Ok(MoreThanText { + session: [ENTRY.to_string()].to_vec(), + channel: s, + }) +} + +#[cfg(test)] +mod db_start_up { + use super::*; + use tempfile::tempdir; + + #[async_std::test] + async fn initial_session() { + let dir = tempdir().unwrap(); + let mtt = start_db(dir.path()).await.unwrap(); + assert_eq!(mtt.session, [ENTRY]); + } +}