-
Notifications
You must be signed in to change notification settings - Fork 5
/
state.rs
30 lines (23 loc) · 1008 Bytes
/
state.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use rusqlite::Connection;
use tauri::{AppHandle, State, Manager};
pub struct AppState {
pub db: std::sync::Mutex<Option<Connection>>,
}
pub trait ServiceAccess {
fn db<F, TResult>(&self, operation: F) -> TResult where F: FnOnce(&Connection) -> TResult;
fn db_mut<F, TResult>(&self, operation: F) -> TResult where F: FnOnce(&mut Connection) -> TResult;
}
impl ServiceAccess for AppHandle {
fn db<F, TResult>(&self, operation: F) -> TResult where F: FnOnce(&Connection) -> TResult {
let app_state: State<AppState> = self.state();
let db_connection_guard = app_state.db.lock().unwrap();
let db = db_connection_guard.as_ref().unwrap();
operation(db)
}
fn db_mut<F, TResult>(&self, operation: F) -> TResult where F: FnOnce(&mut Connection) -> TResult {
let app_state: State<AppState> = self.state();
let mut db_connection_guard = app_state.db.lock().unwrap();
let db = db_connection_guard.as_mut().unwrap();
operation(db)
}
}