rust 用actix-web和mysql实现结果中的结果

qaxu7uf2  于 2022-12-19  发布在  Mysql
关注(0)|答案(1)|浏览(309)

我对rust非常非常陌生(来自c++ & go),我正在尝试实现一个由mysql数据库支持的简单rest API来学习这门语言。
我遵循了actix中的各种示例(例如https://github.com/auth0-blog/actix-diesel-auth/blob/master/src/handlers.rs),得出了以下结论:

use std::vec::Vec;
use actix_web::{web, HttpResponse};
use mysql::*;
use mysql::prelude::Queryable;

use crate::models::{self, user::User};

// Handler for GET /users
pub async fn get_users(pool: mysql::Pool) -> HttpResponse {

    let op =  web::block(move || 
        get_all_watches(pool)).await;

    match op {
        Ok(users) => {

            match users {
                Ok(users) => HttpResponse::Ok().json(users),
                Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
            }
        },
        Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
    }

}

fn get_all_users(pool: mysql::Pool) -> Result<Vec<models::user::User>> {

    let mut conn = pool.get_conn()?;

    let watches = conn
    .query_map(
        "SELECT userId, name, fisrtname, email from users",
        |(user_id, name, firstname, email)| {
            User { user_id, name, firstname, email }
        },
    )?;

    Ok(watches)
}

get_all_users返回从web::block Package 到Result<Result<Vec<Watch, Global>, Error>, BlockingError>中的Result<Vec<Watch, Global>, Error>
我发现match { match {对于这样一个简单的操作来说是相当不优雅的。当从actix直接与数据库交互时(没有像auth0示例中那样将Diesel作为ORM),web::block是“正确的”吗?有没有一种惯用的方法来处理这个流?

rta7y2nd

rta7y2nd1#

当您看到嵌套的match时,通常可以将其转换为一个match

match op {
    Ok(Ok(users)) => HttpResponse::Ok().json(users),
    Ok(Err(err)) => HttpResponse::InternalServerError().body(err.to_string()),
    Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
}

相关问题