Skip to content

Commit 3cd585b

Browse files
committed
Added JSON-based repository
1 parent 23f8bc3 commit 3cd585b

File tree

3 files changed

+75
-2
lines changed

3 files changed

+75
-2
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
use serde::Serialize;
2+
use serde::de::DeserializeOwned;
3+
use std::collections::HashMap;
4+
use std::env;
5+
use std::fs::{File, OpenOptions};
6+
use std::io::{Read, Write};
7+
8+
fn get_store() -> Result<File, String> {
9+
let file_path = env::var("STORAGE_PATH").unwrap_or("works.json".to_string());
10+
11+
let f = OpenOptions::new()
12+
.read(true)
13+
.write(true)
14+
.create(true)
15+
.open(&file_path)
16+
.map_err(|e| e.to_string())?;
17+
18+
Ok(f)
19+
}
20+
21+
pub fn get_all<T>() -> Result<HashMap<String, T>, String>
22+
where
23+
T: DeserializeOwned,
24+
{
25+
let mut data_file = get_store()?;
26+
let mut contents = String::new();
27+
data_file
28+
.read_to_string(&mut contents)
29+
.map_err(|e| e.to_string())?;
30+
let work_items: HashMap<String, T> =
31+
serde_json::from_str(&contents).map_err(|e| e.to_string())?;
32+
Ok(work_items)
33+
}
34+
35+
pub fn get_by_id<T>(key: &str) -> Result<T, String>
36+
where
37+
T: DeserializeOwned + Clone,
38+
{
39+
let work_items = get_all::<T>()?;
40+
match work_items.get(key) {
41+
Some(wi) => Ok(wi.clone()),
42+
None => Err(format!("Work item with key '{}' not found", key)),
43+
}
44+
}
45+
46+
pub fn save_all<T>(work_items: &HashMap<String, T>) -> Result<(), String>
47+
where
48+
T: Serialize,
49+
{
50+
let mut data_file = get_store()?;
51+
let json_data = serde_json::to_string_pretty(work_items).map_err(|e| e.to_string())?;
52+
data_file
53+
.write_all(json_data.as_bytes())
54+
.map_err(|e| e.to_string())?;
55+
Ok(())
56+
}
57+
58+
pub fn save_single<T>(key: &str, work_item: &T) -> Result<(), String>
59+
where
60+
T: Serialize + DeserializeOwned + Clone,
61+
{
62+
let mut work_items = get_all::<T>().unwrap_or_else(|_| HashMap::new());
63+
work_items.insert(key.to_string(), work_item.clone());
64+
save_all(&work_items)
65+
}
66+
67+
pub fn delete<T>(key: &str) -> Result<(), String>
68+
where
69+
T: Serialize + DeserializeOwned + Clone,
70+
{
71+
let mut work_items = get_all::<T>().unwrap_or(HashMap::new());
72+
work_items.remove(key);
73+
save_all(&work_items)
74+
}

src/planner/dal/src/json_store.rs

Lines changed: 0 additions & 1 deletion
This file was deleted.

src/planner/dal/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// json_store modülü eğer bu feature ile build edilirse kullanılabilir
22
#[cfg(feature = "json-store")]
3-
pub mod json_store;
3+
pub mod json_repository;
44

55
// pub fn add(left: u64, right: u64) -> u64 {
66
// left + right

0 commit comments

Comments
 (0)