rust中的命令未通过invoke调用,无错误消息

6ss1mwsb  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(194)

我从前端调用了3个命令,其中2个运行良好,第3个不行。问题在于函数tournament_search
main.rs:

fn main() {
    tauri::Builder::default()
        .manage(ApiKey {key: Default::default()})
        .invoke_handler(tauri::generate_handler![set_api_key, check_connection, tournament_search])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[tauri::command]
fn set_api_key(key: String , state: State<ApiKey>){
    let mut api_key = state.key.lock().unwrap();
    *api_key = key;
}

#[tauri::command]
async fn check_connection(api_key: State<'_, ApiKey>) -> Result<bool, ()> {
    let key = api_key.key.lock().unwrap().clone();
    let res = Client::new().get(API_URL).bearer_auth(key).send().await.unwrap().text().await.unwrap();
    let json: Value = serde_json::from_str(res.as_str()).unwrap();
    match json["success"].as_bool() {
        Some(_x) => Ok(false),
        None => Ok(true)
    }
}

#[tauri::command]
async fn tournament_search(search_string: String, api_key: State<'_, ApiKey>) -> Result<&str, ()> {
    println!("test: {}", search_string);
    let key = api_key.key.lock().unwrap().clone();
    let mut query: String = String::new();
    query.push_str("query($name:String){tournaments(query:{filter:{name:$name}}){nodes{name,slug,id}}},{$name:");
    query.push_str(search_string.as_str());
    query.push_str("}");
    let res = Client::new().get(API_URL).bearer_auth(key).body(query).send().await.unwrap().text().await.unwrap();
    println!("{}", res);

    Ok("")
}

index.js:

const { invoke } = window.__TAURI__.tauri

window.addEventListener("load", (ev) => {
    let test = document.getElementById("test");
    let apiKey = document.getElementById("apiKey");
    let tournamentSearch = document.getElementById("tournamentSearch");
    let tourneyList = document.getElementById("tourneyList");

    apiKey.addEventListener("input", (ev) => {
        invoke("set_api_key", {key: apiKey.value});
        invoke("check_connection").then((res) => {
            if(res){
                tournamentSearch.disabled = false;            
            }else{
                tournamentSearch.disabled = true;
            }
        });
    });

    tournamentSearch.addEventListener("input", (ev) => {
        test.innerText = "e";
        invoke('tournament_search', {search_string: tournamentSearch.value}).then((res) => {
            test.innerText = res;
        });
    });

});

已经查找了零宽度字符,是否在js中调用了事件get等。问题只是函数没有被调用。

h79rfbju

h79rfbju1#

通过将.catch()添加到invoke调用中,您只会看到一条错误消息。
总之,这里的问题是Tauri将命令参数转换为rust端的camelCase(以匹配JS默认值),因此它将是{ searchString: tournamentSearch.value }
如果你更喜欢snake_case,你可以通过如下修改命令告诉Tauri使用它作为参数:

#[tauri::command(rename_all = "snake_case")]

相关问题