refactor(tauri): Use macro and new Request trait for command generation

This commit is contained in:
binarybaron 2024-08-26 15:26:21 +02:00
parent 9b0023174b
commit d54f5c6c77
No known key found for this signature in database
GPG key ID: 99B75D3E1476A26E
3 changed files with 73 additions and 82 deletions

View file

@ -1,7 +1,7 @@
{ {
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "Capability for the main window", "description": "Capability for the main window",
"windows": ["main"], "windows": ["main"],
"permissions": [] "permissions": ["core:event:allow-emit", "core:event:default"]
} }

View file

@ -3,15 +3,14 @@ use std::sync::Arc;
use swap::{ use swap::{
api::{ api::{
request::{ request::{
get_balance as get_balance_impl, get_swap_infos_all as get_swap_infos_all_impl, BalanceArgs, BuyXmrArgs, GetHistoryArgs, ResumeSwapArgs, SuspendCurrentSwapArgs,
withdraw_btc as withdraw_btc_impl, BalanceArgs, BalanceResponse, GetSwapInfoResponse, WithdrawBtcArgs,
WithdrawBtcArgs, WithdrawBtcResponse,
}, },
Context, Context,
}, },
cli::command::{Bitcoin, Monero}, cli::command::{Bitcoin, Monero},
}; };
use tauri::{Manager, RunEvent, State}; use tauri::{Manager, RunEvent};
trait ToStringResult<T> { trait ToStringResult<T> {
fn to_string_result(self) -> Result<T, String>; fn to_string_result(self) -> Result<T, String>;
@ -20,57 +19,44 @@ trait ToStringResult<T> {
// Implement the trait for Result<T, E> // Implement the trait for Result<T, E>
impl<T, E: ToString> ToStringResult<T> for Result<T, E> { impl<T, E: ToString> ToStringResult<T> for Result<T, E> {
fn to_string_result(self) -> Result<T, String> { fn to_string_result(self) -> Result<T, String> {
match self { self.map_err(|e| e.to_string())
Ok(value) => Ok(value),
Err(err) => Err(err.to_string()),
}
} }
} }
#[tauri::command] /// This macro is used to create boilerplate functions as tauri commands
async fn get_balance(context: State<'_, Arc<Context>>) -> Result<BalanceResponse, String> { /// that simply delegate handling to the respective request type.
get_balance_impl( ///
BalanceArgs { /// # Example
force_refresh: true, /// ```ignored
}, /// tauri_command!(get_balance, BalanceArgs);
context.inner().clone(), /// ```
) /// will resolve to
.await /// ```ignored
.to_string_result() /// #[tauri::command]
} /// async fn get_balance(context: tauri::State<'...>, args: BalanceArgs) -> Result<BalanceArgs::Response, String> {
/// args.handle(context.inner().clone()).await.to_string_result()
#[tauri::command] /// }
async fn get_swap_infos_all( /// ```
context: State<'_, Arc<Context>>, macro_rules! tauri_command {
) -> Result<Vec<GetSwapInfoResponse>, String> { ($fn_name:ident, $request_name:ident) => {
get_swap_infos_all_impl(context.inner().clone())
.await
.to_string_result()
}
/*macro_rules! tauri_command {
($command_name:ident, $command_args:ident, $command_response:ident) => {
#[tauri::command] #[tauri::command]
async fn $command_name( async fn $fn_name(
context: State<'_, Context>, context: tauri::State<'_, Arc<Context>>,
args: $command_args, args: $request_name,
) -> Result<$command_response, String> { ) -> Result<<$request_name as swap::api::request::Request>::Response, String> {
swap::api::request::$command_name(args, context) <$request_name as swap::api::request::Request>::request(args, context.inner().clone())
.await .await
.to_string_result() .to_string_result()
} }
}; };
}*/
#[tauri::command]
async fn withdraw_btc(
context: State<'_, Arc<Context>>,
args: WithdrawBtcArgs,
) -> Result<WithdrawBtcResponse, String> {
withdraw_btc_impl(args, context.inner().clone())
.await
.to_string_result()
} }
tauri_command!(get_balance, BalanceArgs);
tauri_command!(get_swap_infos_all, BalanceArgs);
tauri_command!(buy_xmr, BuyXmrArgs);
tauri_command!(get_history, GetHistoryArgs);
tauri_command!(resume_swap, ResumeSwapArgs);
tauri_command!(withdraw_btc, WithdrawBtcArgs);
tauri_command!(suspend_current_swap, SuspendCurrentSwapArgs);
fn setup<'a>(app: &'a mut tauri::App) -> Result<(), Box<dyn std::error::Error>> { fn setup<'a>(app: &'a mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
tauri::async_runtime::block_on(async { tauri::async_runtime::block_on(async {
@ -90,7 +76,8 @@ fn setup<'a>(app: &'a mut tauri::App) -> Result<(), Box<dyn std::error::Error>>
None, None,
) )
.await .await
.unwrap(); .unwrap()
.with_tauri_handle(app.app_handle().to_owned());
app.manage(Arc::new(context)); app.manage(Arc::new(context));
}); });
@ -104,7 +91,11 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
get_balance, get_balance,
get_swap_infos_all, get_swap_infos_all,
withdraw_btc withdraw_btc,
buy_xmr,
resume_swap,
get_history,
suspend_current_swap
]) ])
.setup(setup) .setup(setup)
.build(tauri::generate_context!()) .build(tauri::generate_context!())

View file

@ -1,32 +1,32 @@
{ {
"productName": "unstoppableswap-gui-rs", "productName": "unstoppableswap-gui-rs",
"version": "0.1.0", "version": "0.1.0",
"identifier": "net.unstoppableswap.gui", "identifier": "net.unstoppableswap.gui",
"build": { "build": {
"devUrl": "http://localhost:1420", "devUrl": "http://localhost:1420",
"frontendDist": "../src-gui/dist" "frontendDist": "../src-gui/dist"
}, },
"app": { "app": {
"windows": [ "windows": [
{ {
"title": "unstoppableswap-gui-rs", "title": "unstoppableswap-gui-rs",
"width": 800, "width": 800,
"height": 600 "height": 600
} }
], ],
"security": { "security": {
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http://localhost:1234" "csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http://localhost:1234 https://api.unstoppableswap.net"
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
} }
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
} }