Split out backends from database

This commit is contained in:
Wojciech Kozlowski 2023-04-14 16:15:25 +02:00
parent f3763f3ca1
commit c87e710d69
4 changed files with 34 additions and 29 deletions

View File

@ -0,0 +1,30 @@
//! Module for storing MusicHoard data in a JSON file database.
use std::fs;
use std::path::PathBuf;
use super::JsonDatabaseBackend;
/// JSON database backend that uses a local file for persistent storage.
pub struct JsonDatabaseFileBackend {
path: PathBuf,
}
impl JsonDatabaseFileBackend {
/// Create a [`JsonDatabaseFileBackend`] that will read/write to the provided path.
pub fn new<P: Into<PathBuf>>(path: P) -> Self {
JsonDatabaseFileBackend { path: path.into() }
}
}
impl JsonDatabaseBackend for JsonDatabaseFileBackend {
fn read(&self) -> Result<String, std::io::Error> {
// Read entire file to memory as for now this is faster than a buffered read from disk:
// https://github.com/serde-rs/json/issues/160
fs::read_to_string(&self.path)
}
fn write(&mut self, json: &str) -> Result<(), std::io::Error> {
fs::write(&self.path, json)
}
}

View File

@ -1,8 +1,5 @@
//! Module for storing MusicHoard data in a JSON file database.
use std::fs;
use std::path::PathBuf;
use serde::de::DeserializeOwned;
use serde::Serialize;
@ -11,6 +8,8 @@ use mockall::automock;
use super::{Database, Error};
pub mod backend;
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Error {
Error::SerDeError(err.to_string())
@ -53,30 +52,6 @@ impl<JDB: JsonDatabaseBackend> Database for JsonDatabase<JDB> {
}
}
/// JSON database backend that uses a local file for persistent storage.
pub struct JsonDatabaseFileBackend {
path: PathBuf,
}
impl JsonDatabaseFileBackend {
/// Create a [`JsonDatabaseFileBackend`] that will read/write to the provided path.
pub fn new<P: Into<PathBuf>>(path: P) -> Self {
JsonDatabaseFileBackend { path: path.into() }
}
}
impl JsonDatabaseBackend for JsonDatabaseFileBackend {
fn read(&self) -> Result<String, std::io::Error> {
// Read entire file to memory as for now this is faster than a buffered read from disk:
// https://github.com/serde-rs/json/issues/160
fs::read_to_string(&self.path)
}
fn write(&mut self, json: &str) -> Result<(), std::io::Error> {
fs::write(&self.path, json)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;

View File

@ -7,7 +7,7 @@ use structopt::StructOpt;
use musichoard::{
collection::MhCollectionManager,
database::{
json::{JsonDatabase, JsonDatabaseFileBackend},
json::{backend::JsonDatabaseFileBackend, JsonDatabase},
Database,
},
library::{

View File

@ -2,7 +2,7 @@ use std::{fs, path::PathBuf};
use musichoard::{
database::{
json::{JsonDatabase, JsonDatabaseFileBackend},
json::{backend::JsonDatabaseFileBackend, JsonDatabase},
Database,
},
Artist,