use microrm::prelude::*; use microrm::Stored; use crate::models::conversation::{self, Conversation, ConversationID}; use std::error::Error; pub struct ChatDatabase { db: DB, } #[derive(Database)] struct DB { conversations: microrm::IDMap, } impl ChatDatabase { pub fn new_in_memory() -> Result> { let db = DB::open_path(":memory:")?; return Ok(Self { db: db, }) } pub fn insert_conversation(&self, conversation: Conversation) -> Result { // First see if conversation guid already exists, update it if so let guid = &conversation.guid; let mut existing = self.db.conversations .with(Conversation::Guid, guid) .get()?; if let Some(existing) = existing.first_mut() { existing.display_name = conversation.display_name; existing.sync(); return Ok(existing.id()); } else { // Otherwise, insert. return self.db.conversations.insert(conversation); } } pub fn get_conversation_by_id(&self, id: ConversationID) -> Result, microrm::Error> { self.db.conversations .by_id(id) .map(|stored_conversation| stored_conversation .map(|stored| stored.wrapped()) ) } pub fn get_conversation_by_guid(&self, guid: &str) -> Result, microrm::Error> { self.db.conversations .with(Conversation::Guid, guid) .get() .and_then(|v| Ok(v .into_iter() .map(|c| c.wrapped()) .last() )) } pub fn all_conversations(&self) -> Result, microrm::Error> { self.db.conversations .get() .map(|v| v .into_iter() .map(|c| c.wrapped()) .collect() ) } fn stored_conversation_by_guid(&self, guid: &str) -> Result>, microrm::Error> { self.db.conversations .with(Conversation::Guid, guid) .get() .map(|v| v .into_iter() .last() ) } }