refactor: use builder style (#50)

* refactor(upload): use plugin builder style

* refactor(sql): use builder style

* refactor(fs-watch): use builder style

* refactor(fs-extra): use builder style

* refactor(auth): use builder style

* fmt

* fmt

Co-authored-by: FabianLars <fabianlars@fabianlars.de>
pull/66/head
Jonas Kruckenberg 3 years ago committed by GitHub
parent 66dc508f34
commit 2d670f70d9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -2,7 +2,7 @@ import { invoke } from "@tauri-apps/api/tauri";
export class Authenticator { export class Authenticator {
async init(): Promise<void> { async init(): Promise<void> {
return await invoke("plugin:authenticator|init"); return await invoke("plugin:authenticator|init_auth");
} }
async register(challenge: string, application: string): Promise<string> { async register(challenge: string, application: string): Promise<string> {

@ -6,13 +6,16 @@ mod auth;
mod error; mod error;
mod u2f; mod u2f;
use tauri::{plugin::Plugin, Invoke, Runtime}; use tauri::{
plugin::{Builder as PluginBuilder, TauriPlugin},
Runtime,
};
pub use error::Error; pub use error::Error;
type Result<T> = std::result::Result<T, Error>; type Result<T> = std::result::Result<T, Error>;
#[tauri::command] #[tauri::command]
fn init() { fn init_auth() {
auth::init_usb(); auth::init_usb();
} }
@ -60,30 +63,14 @@ fn verify_signature(
) )
} }
pub struct TauriAuthenticator<R: Runtime> { pub fn init<R: Runtime>() -> TauriPlugin<R> {
invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>, PluginBuilder::new("authenticator")
} .invoke_handler(tauri::generate_handler![
init_auth,
impl<R: Runtime> Default for TauriAuthenticator<R> {
fn default() -> Self {
Self {
invoke_handler: Box::new(tauri::generate_handler![
init,
register, register,
verify_registration, verify_registration,
sign, sign,
verify_signature verify_signature
]), ])
} .build()
}
}
impl<R: Runtime> Plugin<R> for TauriAuthenticator<R> {
fn name(&self) -> &'static str {
"authenticator"
}
fn extend_api(&mut self, invoke: Invoke<R>) {
(self.invoke_handler)(invoke)
}
} }

@ -3,7 +3,11 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
use serde::{ser::Serializer, Serialize}; use serde::{ser::Serializer, Serialize};
use tauri::{command, plugin::Plugin, Invoke, Runtime}; use tauri::{
command,
plugin::{Builder as PluginBuilder, TauriPlugin},
Runtime,
};
use std::{ use std::{
path::PathBuf, path::PathBuf,
@ -121,25 +125,8 @@ async fn exists(path: PathBuf) -> bool {
path.exists() path.exists()
} }
/// Tauri plugin. pub fn init<R: Runtime>() -> TauriPlugin<R> {
pub struct FsExtra<R: Runtime> { PluginBuilder::new("fs-extra")
invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>, .invoke_handler(tauri::generate_handler![exists, metadata])
} .build()
impl<R: Runtime> Default for FsExtra<R> {
fn default() -> Self {
Self {
invoke_handler: Box::new(tauri::generate_handler![exists, metadata]),
}
}
}
impl<R: Runtime> Plugin<R> for FsExtra<R> {
fn name(&self) -> &'static str {
"fs-extra"
}
fn extend_api(&mut self, message: Invoke<R>) {
(self.invoke_handler)(message)
}
} }

@ -3,8 +3,11 @@ use notify::{
Watcher as _, Watcher as _,
}; };
use serde::{ser::Serializer, Deserialize, Serialize}; use serde::{ser::Serializer, Deserialize, Serialize};
use serde_json::Value as JsonValue; use tauri::{
use tauri::{command, plugin::Plugin, AppHandle, Invoke, Manager, Runtime, State, Window}; command,
plugin::{Builder as PluginBuilder, TauriPlugin},
Manager, Runtime, State, Window,
};
use std::{ use std::{
collections::HashMap, collections::HashMap,
@ -160,30 +163,12 @@ async fn unwatch(watchers: State<'_, WatcherCollection>, id: Id) -> Result<()> {
Ok(()) Ok(())
} }
/// Tauri plugin. pub fn init<R: Runtime>() -> TauriPlugin<R> {
pub struct Watcher<R: Runtime> { PluginBuilder::new("fs-watch")
invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>, .invoke_handler(tauri::generate_handler![watch, unwatch])
} .setup(|app| {
impl<R: Runtime> Default for Watcher<R> {
fn default() -> Self {
Self {
invoke_handler: Box::new(tauri::generate_handler![watch, unwatch]),
}
}
}
impl<R: Runtime> Plugin<R> for Watcher<R> {
fn name(&self) -> &'static str {
"fs-watch"
}
fn initialize(&mut self, app: &AppHandle<R>, _config: JsonValue) -> tauri::plugin::Result<()> {
app.manage(WatcherCollection::default()); app.manage(WatcherCollection::default());
Ok(()) Ok(())
} })
.build()
fn extend_api(&mut self, message: Invoke<R>) {
(self.invoke_handler)(message)
}
} }

@ -14,8 +14,8 @@ use sqlx::{
}; };
use tauri::{ use tauri::{
command, command,
plugin::{Plugin, Result as PluginResult}, plugin::{Builder as PluginBuilder, TauriPlugin},
AppHandle, Invoke, Manager, RunEvent, Runtime, State, AppHandle, Manager, RunEvent, Runtime, State,
}; };
use tokio::sync::Mutex; use tokio::sync::Mutex;
@ -92,7 +92,7 @@ struct DbInstances(Mutex<HashMap<String, Pool<Db>>>);
struct Migrations(Mutex<HashMap<String, MigrationList>>); struct Migrations(Mutex<HashMap<String, MigrationList>>);
#[derive(Default, Deserialize)] #[derive(Default, Deserialize)]
struct PluginConfig { pub struct PluginConfig {
#[serde(default)] #[serde(default)]
preload: Vec<String>, preload: Vec<String>,
} }
@ -300,49 +300,31 @@ async fn select(
Ok(values) Ok(values)
} }
/// Tauri SQL plugin. /// Tauri SQL plugin builder.
pub struct TauriSql<R: Runtime> { pub struct Builder {
migrations: Option<HashMap<String, MigrationList>>, migrations: Option<HashMap<String, MigrationList>>,
invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>,
} }
impl<R: Runtime> Default for TauriSql<R> { impl Builder {
fn default() -> Self {
Self {
migrations: Some(Default::default()),
invoke_handler: Box::new(tauri::generate_handler![load, execute, select, close]),
}
}
}
impl<R: Runtime> TauriSql<R> {
/// Add migrations to a database. /// Add migrations to a database.
#[must_use] #[must_use]
pub fn add_migrations(mut self, db_url: &str, migrations: Vec<Migration>) -> Self { pub fn add_migrations(mut self, db_url: &str, migrations: Vec<Migration>) -> Self {
self.migrations self.migrations
.as_mut() .get_or_insert(Default::default())
.unwrap()
.insert(db_url.to_string(), MigrationList(migrations)); .insert(db_url.to_string(), MigrationList(migrations));
self self
} }
}
impl<R: Runtime> Plugin<R> for TauriSql<R> {
fn name(&self) -> &'static str {
"sql"
}
fn initialize(&mut self, app: &AppHandle<R>, config: serde_json::Value) -> PluginResult<()> { pub fn build<R: Runtime>(mut self) -> TauriPlugin<R, Option<PluginConfig>> {
tauri::async_runtime::block_on(async move { PluginBuilder::new("sql")
let config: PluginConfig = if config.is_null() { .invoke_handler(tauri::generate_handler![load, execute, select, close])
Default::default() .setup_with_config(|app, config: Option<PluginConfig>| {
} else { let config = config.unwrap_or_default();
serde_json::from_value(config)?
};
#[cfg(feature = "sqlite")] #[cfg(feature = "sqlite")]
create_dir_all(app_path(app)).expect("problems creating App directory!"); create_dir_all(app_path(app)).expect("problems creating App directory!");
tauri::async_runtime::block_on(async move {
let instances = DbInstances::default(); let instances = DbInstances::default();
let mut lock = instances.0.lock().await; let mut lock = instances.0.lock().await;
for db in config.preload { for db in config.preload {
@ -363,17 +345,14 @@ impl<R: Runtime> Plugin<R> for TauriSql<R> {
lock.insert(db, pool); lock.insert(db, pool);
} }
drop(lock); drop(lock);
app.manage(instances); app.manage(instances);
app.manage(Migrations(Mutex::new(self.migrations.take().unwrap()))); app.manage(Migrations(Mutex::new(self.migrations.take().unwrap())));
Ok(()) Ok(())
}) })
} })
.on_event(|app, event| {
fn extend_api(&mut self, message: Invoke<R>) {
(self.invoke_handler)(message)
}
fn on_event(&mut self, app: &AppHandle<R>, event: &RunEvent) {
if let RunEvent::Exit = event { if let RunEvent::Exit = event {
tauri::async_runtime::block_on(async move { tauri::async_runtime::block_on(async move {
let instances = &*app.state::<DbInstances>(); let instances = &*app.state::<DbInstances>();
@ -383,5 +362,7 @@ impl<R: Runtime> Plugin<R> for TauriSql<R> {
} }
}); });
} }
})
.build()
} }
} }

@ -4,7 +4,11 @@
use futures::TryStreamExt; use futures::TryStreamExt;
use serde::{ser::Serializer, Serialize}; use serde::{ser::Serializer, Serialize};
use tauri::{command, plugin::Plugin, Invoke, Runtime, Window}; use tauri::{
command,
plugin::{Builder as PluginBuilder, TauriPlugin},
Runtime, Window,
};
use tokio::fs::File; use tokio::fs::File;
use tokio_util::codec::{BytesCodec, FramedRead}; use tokio_util::codec::{BytesCodec, FramedRead};
@ -82,25 +86,8 @@ fn file_to_body<R: Runtime>(id: u32, window: Window<R>, file: File) -> reqwest::
)) ))
} }
/// Tauri plugin. pub fn init<R: Runtime>() -> TauriPlugin<R> {
pub struct Upload<R: Runtime> { PluginBuilder::new("upload")
invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>, .invoke_handler(tauri::generate_handler![upload])
} .build()
impl<R: Runtime> Default for Upload<R> {
fn default() -> Self {
Self {
invoke_handler: Box::new(tauri::generate_handler![upload]),
}
}
}
impl<R: Runtime> Plugin<R> for Upload<R> {
fn name(&self) -> &'static str {
"upload"
}
fn extend_api(&mut self, message: Invoke<R>) {
(self.invoke_handler)(message)
}
} }

Loading…
Cancel
Save