Create utility functions
This commit is contained in:
76
server/src/utils/db_path.rs
Normal file
76
server/src/utils/db_path.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use crate::utils::error::{internal_error, AppResult};
|
||||
use std::fs;
|
||||
|
||||
pub fn get_database_path() -> AppResult<String> {
|
||||
let db_dir = "data/db";
|
||||
let db_path = format!("{}/arkendro.db", db_dir);
|
||||
|
||||
if let Err(e) = fs::create_dir_all(db_dir) {
|
||||
return Err(internal_error(&format!(
|
||||
"Failed to create database directory: {}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(db_path)
|
||||
}
|
||||
|
||||
pub fn ensure_data_directories() -> AppResult<()> {
|
||||
let directories = ["data", "data/db", "data/backups", "data/logs"];
|
||||
|
||||
for dir in directories.iter() {
|
||||
if let Err(e) = fs::create_dir_all(dir) {
|
||||
return Err(internal_error(&format!(
|
||||
"Failed to create directory '{}': {}",
|
||||
dir, e
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_data_path(filename: &str) -> String {
|
||||
format!("data/{}", filename)
|
||||
}
|
||||
|
||||
pub fn get_backup_path(filename: &str) -> String {
|
||||
format!("data/backups/{}", filename)
|
||||
}
|
||||
|
||||
pub fn get_log_path(filename: &str) -> String {
|
||||
format!("data/logs/{}", filename)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn test_database_path_creation() {
|
||||
let _ = fs::remove_dir_all("data");
|
||||
|
||||
let db_path = get_database_path().expect("Should create database path");
|
||||
assert_eq!(db_path, "data/db/arkendro.db");
|
||||
|
||||
assert!(Path::new("data/db").exists());
|
||||
|
||||
let _ = fs::remove_dir_all("data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ensure_data_directories() {
|
||||
let _ = fs::remove_dir_all("data");
|
||||
|
||||
ensure_data_directories().expect("Should create all directories");
|
||||
|
||||
assert!(Path::new("data").exists());
|
||||
assert!(Path::new("data/db").exists());
|
||||
assert!(Path::new("data/backups").exists());
|
||||
assert!(Path::new("data/logs").exists());
|
||||
|
||||
let _ = fs::remove_dir_all("data");
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user