connect to db on startup
This commit is contained in:
@ -49,4 +49,4 @@ impl Display for RequestError {
|
||||
RequestTooLarge => write!(f, "HTTP request too large"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,10 @@ mod storage;
|
||||
|
||||
|
||||
fn main() {
|
||||
let initial_state = state::AppState::new(state::SessionStatus::Locked, None);
|
||||
let initial_state = match state::AppState::new(state::SessionStatus::Locked, None) {
|
||||
Ok(state) => state,
|
||||
Err(e) => {eprintln!("{}", e); return;}
|
||||
};
|
||||
|
||||
tauri::Builder::default()
|
||||
.manage(initial_state)
|
||||
|
@ -3,6 +3,7 @@ use std::sync::RwLock;
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use tokio::sync::oneshot::Sender;
|
||||
use sqlx::{SqlitePool, sqlite::SqlitePoolOptions, sqlite::SqliteConnectOptions};
|
||||
|
||||
use crate::ipc;
|
||||
use crate::errors::*;
|
||||
@ -38,16 +39,42 @@ pub struct AppState {
|
||||
credentials: RwLock<Option<Credentials>>,
|
||||
request_count: RwLock<u64>,
|
||||
open_requests: RwLock<HashMap<u64, Sender<ipc::Approval>>>,
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(status: SessionStatus, creds: Option<Credentials>) -> Self {
|
||||
AppState {
|
||||
pub fn new(status: SessionStatus, creds: Option<Credentials>) -> Result<Self, sqlx::error::Error> {
|
||||
let conn_opts = SqliteConnectOptions::new()
|
||||
.filename("creddy.db")
|
||||
.create_if_missing(true);
|
||||
let pool_opts = SqlitePoolOptions::new();
|
||||
|
||||
let pool: SqlitePool = tauri::async_runtime::block_on(pool_opts.connect_with(conn_opts))?;
|
||||
tauri::async_runtime::block_on(sqlx::migrate!().run(&pool))?;
|
||||
|
||||
let state = AppState {
|
||||
status: RwLock::new(status),
|
||||
credentials: RwLock::new(creds),
|
||||
request_count: RwLock::new(0),
|
||||
open_requests: RwLock::new(HashMap::new()),
|
||||
pool,
|
||||
};
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
async fn _load_from_db(&self) -> Result<(), sqlx::error::Error> {
|
||||
let row: (i32,) = sqlx::query_as("SELECT COUNT(*) FROM credentials")
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
let mut status = self.status.write().unwrap();
|
||||
if row.0 > 0 {
|
||||
*status = SessionStatus::Locked;
|
||||
}
|
||||
else {
|
||||
*status = SessionStatus::Empty;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register_request(&self, chan: Sender<ipc::Approval>) -> u64 {
|
||||
|
Reference in New Issue
Block a user