Skip to content

Commit 05d7f7d

Browse files
committed
make sure storage file is available
1 parent ab06a8b commit 05d7f7d

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src-tauri/src/commands.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,19 @@ pub struct AppState {
1111
pub storage_file: PathBuf,
1212
}
1313

14+
fn ensure_storage_file(storage_file: &PathBuf) -> Result<(), String> {
15+
if !storage_file.exists() {
16+
// Create an empty JSON file
17+
fs::write(storage_file, "{}").map_err(|e| e.to_string())?;
18+
}
19+
Ok(())
20+
}
21+
1422
#[tauri::command]
1523
pub fn get_item(state: State<AppState>, key: String) -> Result<Option<String>, String> {
1624
let storage_file = state.storage_file.clone();
25+
ensure_storage_file(&storage_file)?;
26+
1727
let data = fs::read_to_string(&storage_file).map_err(|e| e.to_string())?;
1828
let json_data: Value = serde_json::from_str(&data).map_err(|e| e.to_string())?;
1929

@@ -25,6 +35,8 @@ pub fn get_item(state: State<AppState>, key: String) -> Result<Option<String>, S
2535
#[tauri::command]
2636
pub fn set_item(state: State<AppState>, key: String, value: String) -> Result<(), String> {
2737
let storage_file = state.storage_file.clone();
38+
ensure_storage_file(&storage_file)?;
39+
2840
let data = fs::read_to_string(&storage_file).map_err(|e| e.to_string())?;
2941
let mut json_data: Value = serde_json::from_str(&data).map_err(|e| e.to_string())?;
3042

@@ -37,6 +49,8 @@ pub fn set_item(state: State<AppState>, key: String, value: String) -> Result<()
3749
#[tauri::command]
3850
pub fn remove_item(state: State<AppState>, key: String) -> Result<(), String> {
3951
let storage_file = state.storage_file.clone();
52+
ensure_storage_file(&storage_file)?;
53+
4054
let data = fs::read_to_string(&storage_file).map_err(|e| e.to_string())?;
4155
let mut json_data: Value = serde_json::from_str(&data).map_err(|e| e.to_string())?;
4256

@@ -49,6 +63,8 @@ pub fn remove_item(state: State<AppState>, key: String) -> Result<(), String> {
4963
#[tauri::command]
5064
pub fn get_all_items(state: State<AppState>) -> Result<String, String> {
5165
let storage_file = state.storage_file.clone();
66+
ensure_storage_file(&storage_file)?;
67+
5268
let data = fs::read_to_string(&storage_file).unwrap_or_else(|_| "{}".to_string());
5369
Ok(data)
5470
}

0 commit comments

Comments
 (0)