78 lines
2.3 KiB
Rust
78 lines
2.3 KiB
Rust
|
|
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<Conversation>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl ChatDatabase {
|
||
|
|
pub fn new_in_memory() -> Result<Self, Box<dyn Error + Send + Sync>> {
|
||
|
|
let db = DB::open_path(":memory:")?;
|
||
|
|
return Ok(Self {
|
||
|
|
db: db,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn insert_conversation(&self, conversation: Conversation) -> Result<ConversationID, microrm::Error> {
|
||
|
|
// 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<Option<Conversation>, 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<Option<Conversation>, 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<Vec<Conversation>, 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<Option<Stored<Conversation>>, microrm::Error> {
|
||
|
|
self.db.conversations
|
||
|
|
.with(Conversation::Guid, guid)
|
||
|
|
.get()
|
||
|
|
.map(|v| v
|
||
|
|
.into_iter()
|
||
|
|
.last()
|
||
|
|
)
|
||
|
|
}
|
||
|
|
}
|