tenho seguinte código tauri v2 rust use tauri::{command, AppHandle}; use tauri::Manager;…
- User
tenho seguinte código tauri v2 rust
use tauri::{command, AppHandle}; use tauri::Manager; use tauri::Wry; use tauri_plugin_store::{with_store, StoreCollection}; use serde_json::json; use std::path::PathBuf;
// Bring in the encrypt_password module mod encrypt_password; use encrypt_password::{Credentials, hash_password, verify_password};
#[command] async fn save_credentials(app: AppHandle, username: String, password: String) -> Result<(), String> { let stores = app.state::<StoreCollection>(); let path = PathBuf::from("store.bin");
// Hash the password let hashed_password = hash_password(&password).map_err(|e| e.to_string())?; let credentials = Credentials { username: username.clone(), password_hash: hashed_password.clone(), }; // Serialize the credentials to JSON let credentials_json = json!(credentials); // Save to the store with_store(app.clone(), stores, path, |store| { store.insert("credentials".to_string(), credentials_json)?; store.save()?; Ok(()) }).map_err(|e| e.to_string())?; Ok(())}
#[command] async fn load_credentials(app: AppHandle) -> Result<Credentials, String> { let stores = app.state::().await.unwrap(); let path = PathBuf::from("store.bin");
let credentials = with_store(app.clone(), stores, path, |store| { let value = store.get("credentials").ok_or("Credentials not found in store")?; // Deserialize the value back into Credentials let credentials: Credentials = serde_json::from_value(value.clone()).map_err(|e| e.to_string())?; Ok(credentials) }).map_err(|e| e.to_string())?; Ok(credentials)}
#[command] async fn verify_user_password(app: AppHandle, username: String, password: String) -> Result<bool, String> { let credentials = load_credentials(app).await?;
if credentials.username != username { return Ok(false); } let is_valid = verify_password(&credentials.password_hash, &password).map_err(|e| e.to_string())?; Ok(is_valid)}
#[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_store::Builder::default().build()) .setup(|app| { // Perform any setup actions here let handle = app.handle(); let stores = handle.state::(); let path = PathBuf::from("store.bin");
with_store(handle.clone(), stores, path, |store| { // Example: Initialize default values if they don't exist if !store.contains_key("credentials") { // Set default credentials or leave empty store.insert("credentials".to_string(), json!(null))?; store.save()?; } Ok(()) }).map_err(|e| e.to_string())?; Ok(()) }) .invoke_handler(tauri::generate_handler![ save_credentials, load_credentials, verify_user_password ]) .run(tauri::generate_context!()) .expect("error while running tauri application");}
Como corrijo erros recebidos
[{ "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs", "owner": "rustc", "code": { "value": "Click for full compiler diagnostic", "target": { "mid": 1, "external": "rust-analyzer-diagnostics-view:/diagnostic%20message%20%5B0%5D?0#file%3A%2F%2F%2Fc%253A%2FUsers%2Fjonatas%2FDesktop%2FiNovaRO%2FRagnaTales%2Fsrc-tauri%2Fsrc%2Flib.rs", "path": "/diagnostic message [0]", "scheme": "rust-analyzer-diagnostics-view", "query": "0", "fragment": "file:///c%3A/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } }, "severity": 8, "message": "missing generics for struct `StoreCollection`\nexpected 1 generic argument", "source": "rustc", "startLineNumber": 14, "startColumn": 30, "endLineNumber": 14, "endColumn": 45, "relatedInformation": [ { "startLineNumber": 39, "startColumn": 12, "endLineNumber": 39, "endColumn": 27, "message": "struct defined here, with 1 generic parameter: `R`", "resource": "/c:/Users/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tauri-plugin-store-2.0.0-rc.3/src/lib.rs" }, { "startLineNumber": 14, "startColumn": 45, "endLineNumber": 14, "endColumn": 45, "message": "add missing generic argument: `<_>`", "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } ] },{ "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs", "owner": "rustc", "code": { "value": "Click for full compiler diagnostic", "target": { "mid": 1, "path": "/diagnostic message [2]", "scheme": "rust-analyzer-diagnostics-view", "query": "2", "fragment": "file:///c%3A/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } }, "severity": 8, "message": "missing generics for struct
StoreCollection\nexpected 1 generic argument", "source": "rustc", "startLineNumber": 40, "startColumn": 30, "endLineNumber": 40, "endColumn": 45, "relatedInformation": [ { "startLineNumber": 39, "startColumn": 12, "endLineNumber": 39, "endColumn": 27, "message": "struct defined here, with 1 generic parameter:R", "resource": "/c:/Users/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tauri-plugin-store-2.0.0-rc.3/src/lib.rs" }, { "startLineNumber": 40, "startColumn": 45, "endLineNumber": 40, "endColumn": 45, "message": "add missing generic argument:<_>", "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } ] },{ "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs", "owner": "rustc", "code": { "value": "Click for full compiler diagnostic", "target": { "mid": 1, "path": "/diagnostic message [4]", "scheme": "rust-analyzer-diagnostics-view", "query": "4", "fragment": "file:///c%3A/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } }, "severity": 8, "message": "`?` couldn't convert the error to `tauri_plugin_store::Error`\nthe question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait\nthe following other types implement trait `From<T>`:\n <tauri_plugin_store::Error as From<serde_json::Error>>\n <tauri_plugin_store::Error as From<std::io::Error>>\n <tauri_plugin_store::Error as From<tauri::Error>>\nrequired for `Result<_, tauri_plugin_store::Error>` to implement `FromResidual<Result<Infallible, &str>>`", "source": "rustc", "startLineNumber": 44, "startColumn": 85, "endLineNumber": 44, "endColumn": 86 },{ "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs", "owner": "rustc", "code": { "value": "Click for full compiler diagnostic", "target": { "mid": 1, "path": "/diagnostic message [5]", "scheme": "rust-analyzer-diagnostics-view", "query": "5", "fragment": "file:///c%3A/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } }, "severity": 8, "message": "?couldn't convert the error totauri_plugin_store::Error\nthe question mark operation (?) implicitly performs a conversion on the error value using theFromtrait\nthe following other types implement traitFrom<T>:\n <tauri_plugin_store::Error as From<serde_json::Error>>\n <tauri_plugin_store::Error as Fromstd::io::Error>\n <tauri_plugin_store::Error as Fromtauri::Error>\nrequired forResult<_, tauri_plugin_store::Error>to implementFromResidual<Result<Infallible, std::string::String>>", "source": "rustc", "startLineNumber": 46, "startColumn": 104, "endLineNumber": 46, "endColumn": 105 },{ "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs", "owner": "rustc", "code": { "value": "Click for full compiler diagnostic", "target": { "mid": 1, "path": "/diagnostic message [6]", "scheme": "rust-analyzer-diagnostics-view", "query": "6", "fragment": "file:///c%3A/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } }, "severity": 8, "message": "missing generics for struct `StoreCollection`\nexpected 1 generic argument", "source": "rustc", "startLineNumber": 74, "startColumn": 41, "endLineNumber": 74, "endColumn": 56, "relatedInformation": [ { "startLineNumber": 39, "startColumn": 12, "endLineNumber": 39, "endColumn": 27, "message": "struct defined here, with 1 generic parameter: `R`", "resource": "/c:/Users/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tauri-plugin-store-2.0.0-rc.3/src/lib.rs" }, { "startLineNumber": 74, "startColumn": 56, "endLineNumber": 74, "endColumn": 56, "message": "add missing generic argument: `<_>`", "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } ] },{ "resource": "/c:/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs", "owner": "rustc", "code": { "value": "Click for full compiler diagnostic", "target": { "mid": 1, "path": "/diagnostic message [8]", "scheme": "rust-analyzer-diagnostics-view", "query": "8", "fragment": "file:///c%3A/Users/Desktop/iNovaRO/RagnaTales/src-tauri/src/lib.rs" } }, "severity": 8, "message": "no method namedcontains_keyfound for mutable reference&mut Store<tauri_runtime_wry::Wry<EventLoopMessage>>in the current scope\nmethod not found in&mut Store<Wry<EventLoopMessage>>", "source": "rustc", "startLineNumber": 79, "startColumn": 27, "endLineNumber": 79, "endColumn": 39 }] - Assistant
Para corrigir os erros que você está enfrentando no seu código Tauri com Rust, siga os passos abaixo:
-
Adicione os argumentos genéricos ausentes para
StoreCollection:O erro que você está recebendo diz que está faltando um argumento genérico para a struct
StoreCollection. A structStoreCollectionrequer um parâmetro genérico que especifica o tipo de runtime que você está usando, que no seu caso éWry. Você precisa adicionar<Wry>sempre que usarStoreCollection.Correções:
-
No seu método
load_credentials, mude:let stores = app.state::<StoreCollection>().await.unwrap();para
let stores = app.state::<StoreCollection<Wry>>();Nota: Remova
.await.unwrap()poisapp.state()não é uma função assíncrona e não retorna umFuture. -
No método
run, altere:let stores = handle.state::<StoreCollection>();para
let stores = handle.state::<StoreCollection<Wry>>();
-
-
Remova chamadas desnecessárias de
.awaite.unwrap():A função
app.state()é síncrona e não retorna umFuture, portanto não é necessário usar.await. Além disso, usar.unwrap()pode causar um panic se o estado não for encontrado. Como você tem certeza de que o estado existe, pode omitir o.unwrap().Correção:
- No método
load_credentials, remova.await.unwrap()de:
ficando:let stores = app.state::<StoreCollection<Wry>>().await.unwrap();let stores = app.state::<StoreCollection<Wry>>();
- No método
-
Ajuste o tratamento de erros nas closures passadas para
with_store:Conforme o erro indica, o operador
?não consegue converter o erro paratauri_plugin_store::Errorporque está tentando propagar um erro do tipo&strouString, que não implementaFromparatauri_plugin_store::Error.Correções:
-
Quando você usa
ok_orou retorna um erro dentro da closure, certifique-se de que o erro seja do tipo correto. Substitua:let value = store.get("credentials").ok_or("Credentials not found in store")?;por
let value = store.get("credentials").ok_or_else(|| tauri_plugin_store::Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "Credentials not found in store")))?;Isso cria um erro de I/O que pode ser convertido para
tauri_plugin_store::Error. -
Quando você usa
map_err, certifique-se de converter o erro para um tipo que possa ser convertido emtauri_plugin_store::Errorou trate o erro dentro domap_errsem propagar diretamente com?.
-
-
Substitua o método
contains_keyporhas:O método
contains_keynão existe na structStoredotauri-plugin-store. Em vez disso, use o métodohaspara verificar se uma chave existe.Correção:
- No método
run, altere:
paraif !store.contains_key("credentials") {if !store.has("credentials") {
- No método
-
Certifique-se de que todos os tipos de erro são consistentes:
As funções que retornam
Resultdevem ter tipos de erro consistentes. Se você está retornandoResult<_, String>nos seus comandos, mas dentro das closures está lidando comtauri_plugin_store::Error, talvez seja necessário converter esses erros emStringao propagar.Correção:
- Ao final das suas chamadas de
with_store, você já está usandomap_err(|e| e.to_string())?;, o que convertetauri_plugin_store::ErroremString. Certifique-se de que isso seja consistente em todo o código.
- Ao final das suas chamadas de
-
Verifique se há métodos obsoletos ou mudanças na API:
Certifique-se de que está usando a versão correta do
tauri-plugin-storee que todos os métodos que você está chamando existem nessa versão. Consulte a documentação oficial para confirmar.
Aqui está o código corrigido:
use tauri::{command, AppHandle}; use tauri::Manager; use tauri::Wry; use tauri_plugin_store::{with_store, StoreCollection}; use serde_json::json; use std::path::PathBuf; // Importa o módulo encrypt_password mod encrypt_password; use encrypt_password::{Credentials, hash_password, verify_password}; #[command] async fn save_credentials(app: AppHandle<Wry>, username: String, password: String) -> Result<(), String> { let stores = app.state::<StoreCollection<Wry>>(); let path = PathBuf::from("store.bin"); // Hasheia a senha let hashed_password = hash_password(&password).map_err(|e| e.to_string())?; let credentials = Credentials { username: username.clone(), password_hash: hashed_password.clone(), }; // Serializa as credenciais para JSON let credentials_json = json!(credentials); // Salva no store with_store(app.clone(), stores, path, |store| { store.insert("credentials".to_string(), credentials_json)?; store.save()?; Ok(()) }).map_err(|e| e.to_string())?; Ok(()) } #[command] async fn load_credentials(app: AppHandle<Wry>) -> Result<Credentials, String> { let stores = app.state::<StoreCollection<Wry>>(); let path = PathBuf::from("store.bin"); let credentials = with_store(app.clone(), stores, path, |store| { let value = store.get("credentials").ok_or_else(|| { tauri_plugin_store::Error::Io(std::io::Error::new( std::io::ErrorKind::NotFound, "Credentials not found in store", )) })?; // Desserializa o valor de volta para Credentials let credentials: Credentials = serde_json::from_value(value.clone()).map_err(|e| { tauri_plugin_store::Error::Json(e) })?; Ok(credentials) }).map_err(|e| e.to_string())?; Ok(credentials) } #[command] async fn verify_user_password(app: AppHandle<Wry>, username: String, password: String) -> Result<bool, String> { let credentials = load_credentials(app).await?; if credentials.username != username { return Ok(false); } let is_valid = verify_password(&credentials.password_hash, &password).map_err(|e| e.to_string())?; Ok(is_valid) } #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_store::Builder::default().build()) .setup(|app| { // Realiza ações de configuração aqui let handle = app.handle(); let stores = handle.state::<StoreCollection<Wry>>(); let path = PathBuf::from("store.bin"); with_store(handle.clone(), stores, path, |store| { // Exemplo: Inicializa valores padrão se eles não existirem if !store.has("credentials") { // Define credenciais padrão ou deixa vazio store.insert("credentials".to_string(), json!(null))?; store.save()?; } Ok(()) }).map_err(|e| e.to_string())?; Ok(()) }) .invoke_handler(tauri::generate_handler![ save_credentials, load_credentials, verify_user_password ]) .run(tauri::generate_context!()) .expect("erro ao executar a aplicação Tauri"); }Notas importantes:
- Certifique-se de ter importado todos os módulos necessários, especialmente se estiver usando tipos ou funções adicionais.
- Sempre verifique a documentação da versão específica das bibliotecas que você está usando, pois APIs podem mudar entre versões.
- O tratamento adequado de erros é crucial para evitar panics inesperados e garantir que seu aplicativo seja robusto.
Se você tiver mais dúvidas ou enfrentar outros problemas, sinta-se à vontade para perguntar!
-