Private
Public Access
1
0
Files
Kordophone/kordophone-db/src/database.rs

64 lines
1.7 KiB
Rust
Raw Normal View History

use anyhow::Result;
use diesel::prelude::*;
use crate::repository::Repository;
use crate::settings::Settings;
pub use kordophone::api::TokenManagement;
use kordophone::model::JwtToken;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
pub struct Database {
pub connection: SqliteConnection,
}
impl Database {
pub fn new(path: &str) -> Result<Self> {
let mut connection = SqliteConnection::establish(path)?;
connection.run_pending_migrations(MIGRATIONS)
.map_err(|e| anyhow::anyhow!("Error running migrations: {}", e))?;
Ok(Self { connection })
}
pub fn new_in_memory() -> Result<Self> {
Self::new(":memory:")
}
pub fn with_repository<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Repository) -> R,
{
let mut repository = Repository::new(&mut self.connection);
f(&mut repository)
}
pub fn with_settings<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Settings) -> R,
{
let mut settings = Settings::new(&mut self.connection);
f(&mut settings)
}
}
static TOKEN_KEY: &str = "token";
impl TokenManagement for Database {
fn get_token(&mut self) -> Option<JwtToken> {
self.with_settings(|settings| {
let token: Result<Option<JwtToken>> = settings.get(TOKEN_KEY);
match token {
Ok(data) => data,
Err(_) => None,
}
})
}
fn set_token(&mut self, token: JwtToken) {
self.with_settings(|settings| settings.put(TOKEN_KEY, &token).unwrap());
}
}