@@ -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]
1523pub 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]
2636pub 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]
3850pub 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]
5064pub 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