From 2d670f70d9ce6a68b9f75944323fa8584d4ce841 Mon Sep 17 00:00:00 2001 From: Jonas Kruckenberg Date: Sat, 7 Jan 2023 15:53:56 +0100 Subject: [PATCH] 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 --- plugins/authenticator/guest-js/index.ts | 2 +- plugins/authenticator/src/lib.rs | 43 +++------ plugins/fs-extra/src/lib.rs | 31 ++---- plugins/fs-watch/src/lib.rs | 41 +++----- plugins/sql/src/plugin.rs | 123 ++++++++++-------------- plugins/upload/src/lib.rs | 31 ++---- 6 files changed, 99 insertions(+), 172 deletions(-) diff --git a/plugins/authenticator/guest-js/index.ts b/plugins/authenticator/guest-js/index.ts index 6f9da943..8b4a533c 100644 --- a/plugins/authenticator/guest-js/index.ts +++ b/plugins/authenticator/guest-js/index.ts @@ -2,7 +2,7 @@ import { invoke } from "@tauri-apps/api/tauri"; export class Authenticator { async init(): Promise { - return await invoke("plugin:authenticator|init"); + return await invoke("plugin:authenticator|init_auth"); } async register(challenge: string, application: string): Promise { diff --git a/plugins/authenticator/src/lib.rs b/plugins/authenticator/src/lib.rs index bc0d4c35..ef889e21 100644 --- a/plugins/authenticator/src/lib.rs +++ b/plugins/authenticator/src/lib.rs @@ -6,13 +6,16 @@ mod auth; mod error; mod u2f; -use tauri::{plugin::Plugin, Invoke, Runtime}; +use tauri::{ + plugin::{Builder as PluginBuilder, TauriPlugin}, + Runtime, +}; pub use error::Error; type Result = std::result::Result; #[tauri::command] -fn init() { +fn init_auth() { auth::init_usb(); } @@ -60,30 +63,14 @@ fn verify_signature( ) } -pub struct TauriAuthenticator { - invoke_handler: Box) + Send + Sync>, -} - -impl Default for TauriAuthenticator { - fn default() -> Self { - Self { - invoke_handler: Box::new(tauri::generate_handler![ - init, - register, - verify_registration, - sign, - verify_signature - ]), - } - } -} - -impl Plugin for TauriAuthenticator { - fn name(&self) -> &'static str { - "authenticator" - } - - fn extend_api(&mut self, invoke: Invoke) { - (self.invoke_handler)(invoke) - } +pub fn init() -> TauriPlugin { + PluginBuilder::new("authenticator") + .invoke_handler(tauri::generate_handler![ + init_auth, + register, + verify_registration, + sign, + verify_signature + ]) + .build() } diff --git a/plugins/fs-extra/src/lib.rs b/plugins/fs-extra/src/lib.rs index 286e8508..621a28bd 100644 --- a/plugins/fs-extra/src/lib.rs +++ b/plugins/fs-extra/src/lib.rs @@ -3,7 +3,11 @@ // SPDX-License-Identifier: MIT use serde::{ser::Serializer, Serialize}; -use tauri::{command, plugin::Plugin, Invoke, Runtime}; +use tauri::{ + command, + plugin::{Builder as PluginBuilder, TauriPlugin}, + Runtime, +}; use std::{ path::PathBuf, @@ -121,25 +125,8 @@ async fn exists(path: PathBuf) -> bool { path.exists() } -/// Tauri plugin. -pub struct FsExtra { - invoke_handler: Box) + Send + Sync>, -} - -impl Default for FsExtra { - fn default() -> Self { - Self { - invoke_handler: Box::new(tauri::generate_handler![exists, metadata]), - } - } -} - -impl Plugin for FsExtra { - fn name(&self) -> &'static str { - "fs-extra" - } - - fn extend_api(&mut self, message: Invoke) { - (self.invoke_handler)(message) - } +pub fn init() -> TauriPlugin { + PluginBuilder::new("fs-extra") + .invoke_handler(tauri::generate_handler![exists, metadata]) + .build() } diff --git a/plugins/fs-watch/src/lib.rs b/plugins/fs-watch/src/lib.rs index facf3298..790507b7 100644 --- a/plugins/fs-watch/src/lib.rs +++ b/plugins/fs-watch/src/lib.rs @@ -3,8 +3,11 @@ use notify::{ Watcher as _, }; use serde::{ser::Serializer, Deserialize, Serialize}; -use serde_json::Value as JsonValue; -use tauri::{command, plugin::Plugin, AppHandle, Invoke, Manager, Runtime, State, Window}; +use tauri::{ + command, + plugin::{Builder as PluginBuilder, TauriPlugin}, + Manager, Runtime, State, Window, +}; use std::{ collections::HashMap, @@ -160,30 +163,12 @@ async fn unwatch(watchers: State<'_, WatcherCollection>, id: Id) -> Result<()> { Ok(()) } -/// Tauri plugin. -pub struct Watcher { - invoke_handler: Box) + Send + Sync>, -} - -impl Default for Watcher { - fn default() -> Self { - Self { - invoke_handler: Box::new(tauri::generate_handler![watch, unwatch]), - } - } -} - -impl Plugin for Watcher { - fn name(&self) -> &'static str { - "fs-watch" - } - - fn initialize(&mut self, app: &AppHandle, _config: JsonValue) -> tauri::plugin::Result<()> { - app.manage(WatcherCollection::default()); - Ok(()) - } - - fn extend_api(&mut self, message: Invoke) { - (self.invoke_handler)(message) - } +pub fn init() -> TauriPlugin { + PluginBuilder::new("fs-watch") + .invoke_handler(tauri::generate_handler![watch, unwatch]) + .setup(|app| { + app.manage(WatcherCollection::default()); + Ok(()) + }) + .build() } diff --git a/plugins/sql/src/plugin.rs b/plugins/sql/src/plugin.rs index 5440c926..0674f634 100644 --- a/plugins/sql/src/plugin.rs +++ b/plugins/sql/src/plugin.rs @@ -14,8 +14,8 @@ use sqlx::{ }; use tauri::{ command, - plugin::{Plugin, Result as PluginResult}, - AppHandle, Invoke, Manager, RunEvent, Runtime, State, + plugin::{Builder as PluginBuilder, TauriPlugin}, + AppHandle, Manager, RunEvent, Runtime, State, }; use tokio::sync::Mutex; @@ -92,7 +92,7 @@ struct DbInstances(Mutex>>); struct Migrations(Mutex>); #[derive(Default, Deserialize)] -struct PluginConfig { +pub struct PluginConfig { #[serde(default)] preload: Vec, } @@ -300,88 +300,69 @@ async fn select( Ok(values) } -/// Tauri SQL plugin. -pub struct TauriSql { +/// Tauri SQL plugin builder. +pub struct Builder { migrations: Option>, - invoke_handler: Box) + Send + Sync>, } -impl Default for TauriSql { - fn default() -> Self { - Self { - migrations: Some(Default::default()), - invoke_handler: Box::new(tauri::generate_handler![load, execute, select, close]), - } - } -} - -impl TauriSql { +impl Builder { /// Add migrations to a database. #[must_use] pub fn add_migrations(mut self, db_url: &str, migrations: Vec) -> Self { self.migrations - .as_mut() - .unwrap() + .get_or_insert(Default::default()) .insert(db_url.to_string(), MigrationList(migrations)); self } -} - -impl Plugin for TauriSql { - fn name(&self) -> &'static str { - "sql" - } - - fn initialize(&mut self, app: &AppHandle, config: serde_json::Value) -> PluginResult<()> { - tauri::async_runtime::block_on(async move { - let config: PluginConfig = if config.is_null() { - Default::default() - } else { - serde_json::from_value(config)? - }; - #[cfg(feature = "sqlite")] - create_dir_all(app_path(app)).expect("problems creating App directory!"); + pub fn build(mut self) -> TauriPlugin> { + PluginBuilder::new("sql") + .invoke_handler(tauri::generate_handler![load, execute, select, close]) + .setup_with_config(|app, config: Option| { + let config = config.unwrap_or_default(); - let instances = DbInstances::default(); - let mut lock = instances.0.lock().await; - for db in config.preload { #[cfg(feature = "sqlite")] - let fqdb = path_mapper(app_path(app), &db); - #[cfg(not(feature = "sqlite"))] - let fqdb = db.clone(); - - if !Db::database_exists(&fqdb).await.unwrap_or(false) { - Db::create_database(&fqdb).await?; - } - let pool = Pool::connect(&fqdb).await?; - - if let Some(migrations) = self.migrations.as_mut().unwrap().remove(&db) { - let migrator = Migrator::new(migrations).await?; - migrator.run(&pool).await?; - } - lock.insert(db, pool); - } - drop(lock); - app.manage(instances); - app.manage(Migrations(Mutex::new(self.migrations.take().unwrap()))); - Ok(()) - }) - } - - fn extend_api(&mut self, message: Invoke) { - (self.invoke_handler)(message) - } + create_dir_all(app_path(app)).expect("problems creating App directory!"); + + tauri::async_runtime::block_on(async move { + let instances = DbInstances::default(); + let mut lock = instances.0.lock().await; + for db in config.preload { + #[cfg(feature = "sqlite")] + let fqdb = path_mapper(app_path(app), &db); + #[cfg(not(feature = "sqlite"))] + let fqdb = db.clone(); + + if !Db::database_exists(&fqdb).await.unwrap_or(false) { + Db::create_database(&fqdb).await?; + } + let pool = Pool::connect(&fqdb).await?; - fn on_event(&mut self, app: &AppHandle, event: &RunEvent) { - if let RunEvent::Exit = event { - tauri::async_runtime::block_on(async move { - let instances = &*app.state::(); - let instances = instances.0.lock().await; - for value in instances.values() { - value.close().await; + if let Some(migrations) = self.migrations.as_mut().unwrap().remove(&db) { + let migrator = Migrator::new(migrations).await?; + migrator.run(&pool).await?; + } + lock.insert(db, pool); + } + drop(lock); + + app.manage(instances); + app.manage(Migrations(Mutex::new(self.migrations.take().unwrap()))); + + Ok(()) + }) + }) + .on_event(|app, event| { + if let RunEvent::Exit = event { + tauri::async_runtime::block_on(async move { + let instances = &*app.state::(); + let instances = instances.0.lock().await; + for value in instances.values() { + value.close().await; + } + }); } - }); - } + }) + .build() } } diff --git a/plugins/upload/src/lib.rs b/plugins/upload/src/lib.rs index b739435d..a83a87ff 100644 --- a/plugins/upload/src/lib.rs +++ b/plugins/upload/src/lib.rs @@ -4,7 +4,11 @@ use futures::TryStreamExt; 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_util::codec::{BytesCodec, FramedRead}; @@ -82,25 +86,8 @@ fn file_to_body(id: u32, window: Window, file: File) -> reqwest:: )) } -/// Tauri plugin. -pub struct Upload { - invoke_handler: Box) + Send + Sync>, -} - -impl Default for Upload { - fn default() -> Self { - Self { - invoke_handler: Box::new(tauri::generate_handler![upload]), - } - } -} - -impl Plugin for Upload { - fn name(&self) -> &'static str { - "upload" - } - - fn extend_api(&mut self, message: Invoke) { - (self.invoke_handler)(message) - } +pub fn init() -> TauriPlugin { + PluginBuilder::new("upload") + .invoke_handler(tauri::generate_handler![upload]) + .build() }