35 lines
1.1 KiB
Rust
35 lines
1.1 KiB
Rust
//! JSON file–backed `ConversationRepository`.
|
||||
|
|
//! Stores `Conversation` at `<session_dir>/conversation.json`.
|
|||
|
|
|
|||
|
|
use std::path::Path;
|
|||
|
|
|
|||
|
|
use zesdex_domain::cms::{Conversation, ConversationRepository, RepositoryError};
|
|||
|
|
|
|||
|
|
use crate::utils::write_json_atomic;
|
|||
|
|
|
|||
|
|
/// File-based `ConversationRepository` that reads/writes `conversation.json`.
|
|||
|
|
#[derive(Debug, Clone, Default)]
|
|||
|
|
pub struct JsonConversationRepository;
|
|||
|
|
|
|||
|
|
impl JsonConversationRepository {
|
|||
|
|
pub fn new() -> Self {
|
|||
|
|
Self
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
impl ConversationRepository for JsonConversationRepository {
|
|||
|
|
fn load(&self, session_dir: &Path) -> Result<Conversation, RepositoryError> {
|
|||
|
|
let path = session_dir.join("conversation.json");
|
|||
|
|
let data = std::fs::read_to_string(&path)?;
|
|||
|
|
let conv: Conversation = serde_json::from_str(&data)?;
|
|||
|
|
Ok(conv)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
fn save(&self, session_dir: &Path, conversation: &Conversation) -> Result<(), RepositoryError> {
|
|||
|
|
std::fs::create_dir_all(session_dir)?;
|
|||
|
|
let path = session_dir.join("conversation.json");
|
|||
|
|
write_json_atomic(&path, conversation, None)?;
|
|||
|
|
Ok(())
|
|||
|
|
}
|
|||
|
|
}
|