Rust详情修改删除优化
        【摘要】 Rust详情修改删除优化
    
    
    
    Rust详情修改删除优化
详情优化
接下来我们抽离详情接口
🍎旧的写法
之前我们的写法如下
pub async fn get_user_detail(
    pool: web::Data<MySqlPool>,
    path: web::Path<i32>, // user_id
) -> HttpResponse {
    let user_id = path.into_inner();
    let result = sqlx::query_as::<_, User>("SELECT * FROM sys_user WHERE user_id = ?")
        .bind(user_id)
        .fetch_one(pool.get_ref())
        .await;
    match result {
        Ok(user) => {
            let response = ApiDetailResponse {
                code: 200,
                msg: "查询成功",
                data: user, // 返回数据格式可根据实际需求进行修改
            };
            HttpResponse::Ok().json(response)
        }
        Err(sqlx::Error::RowNotFound) => {
            let response = ApiDetailResponse {
                code: 404,
                msg: "用户不存在",
                data: (),
            };
            HttpResponse::NotFound().json(response)
        }
        Err(e) => {
            eprintln!("查询用户详情失败: {:?}", e);
            let response = ApiDetailResponse {
                code: 500,
                msg: "查询失败",
                data: (),
            };
            HttpResponse::InternalServerError().json(response)
        }
    }
}
🍎抽离出来详情方法
// 通用详情
pub async fn detail_api<T>(
    pool: web::Data<MySqlPool>,
    table: &str,
    pk_field: &str,
    id: i32,
) -> HttpResponse
where
    T: for<'r> FromRow<'r, sqlx::mysql::MySqlRow> + serde::Serialize + Unpin + Send,
{
    let query = format!("SELECT * FROM {} WHERE {} = ?", table, pk_field);
    let result = sqlx::query_as::<_, T>(&query)
        .bind(id)
        .fetch_one(pool.get_ref())
        .await;
    match result {
        Ok(data) => HttpResponse::Ok().json(ApiDetailResponse {
            code: 200,
            msg: "查询成功",
            data: data,
        }),
        Err(sqlx::Error::RowNotFound) => HttpResponse::NotFound().json(BasicResponse {
            code: 404,
            msg: "数据不存在"
        }),
        Err(e) => {
            eprintln!("查询详情失败: {:?}", e);
            HttpResponse::InternalServerError().json(BasicResponse {
                code: 500,
                msg: "查询失败"
            })
        }
    }
}
🍎封装使用详情方法
// 通用详情
pub async fn get_user_detail(
    pool: web::Data<MySqlPool>,
    path: web::Path<i32>,
) -> HttpResponse {
    crate::common::apimethods::detail_api::<User>(pool, "sys_user", "user_id", path.into_inner()).await
}
修改优化
🍎现在的修改接口如下面所示
//更新
#[derive(Serialize)]
pub struct Response {
    code: i32,
    msg: String,
}
pub async fn put_update_users(
    pool: web::Data<Pool<MySql>>, 
    item: web::Json<UpdateUserRequest>
) -> impl Responder {
    let result = sqlx::query!(
        "UPDATE sys_user SET age = ? WHERE user_id = ?",
        item.age,
        item.user_id
    )
    .execute(pool.get_ref())
    .await;
    match result {
        Ok(_) => HttpResponse::Ok().json(Response {
            code: 200,
            msg: "更新成功!".to_string(),
        }),
        Err(e) => {
            eprintln!("数据库更新失败: {:?}", e);
            HttpResponse::InternalServerError().json(Response {
                code: 500,
                msg: "更新失败!".to_string(),
            })
        }
    }
}
🍎修改接口以后
pub async fn update_api(
    pool: &MySqlPool,
    table: &str,
    pk_field: &str,
    pk_value: i32,
    data: &HashMap<String, String>,
) -> HttpResponse {
    // 构建 SET 语句
    let sets: Vec<String> = data.keys().map(|k| format!("{} = ?", k)).collect();
    let sql = format!(
        "UPDATE {} SET {} WHERE {} = ?",
        table,
        sets.join(", "),
        pk_field
    );
    let mut query = sqlx::query(&sql);
    for key in data.keys() {
        query = query.bind(data.get(key).unwrap());
    }
    query = query.bind(pk_value);
    match query.execute(pool).await {
        Ok(_) => HttpResponse::Ok().json(Response {
            code: 200,
            msg: "更新成功!".to_string(),
        }),
        Err(e) => {
            eprintln!("数据库更新失败: {:?}", e);
            HttpResponse::InternalServerError().json(Response {
                code: 500,
                msg: "更新失败!".to_string(),
            })
        }
    }
}
🍎测试接口
我们想要的字段可以更改,其他字段无法更改
返回结果如下
{
    "code": 200,
    "msg": "更新成功!"
}
删除优化
接下来我们抽离删除接口
🍎旧的写法
pub async fn delete_user(
    pool: web::Data<Pool<MySql>>, 
    id: web::Path<i32>  // Path 中包含了用户的 ID
) -> impl Responder {
    // 执行删除操作
    let result = sqlx::query!(
        "DELETE FROM sys_user WHERE user_id = ?",
        *id  // 解引用 Path 获取具体的值
    )
    .execute(pool.get_ref())
    .await;
    match result {
        Ok(_) => HttpResponse::Ok().json(BasicResponse {
            code: 200,
            msg: "删除成功!",
        }),
        Err(e) => {
            eprintln!("数据库删除失败: {:?}", e);
            HttpResponse::InternalServerError().json(BasicResponse {
                code: 500,
                msg: "删除失败!",
            })
        }
    }
}
🍎抽离出来删除方法
// 通用删除接口
pub async fn delete_api(
    pool: &MySqlPool,
    table: &str,
    pk_field: &str,
    pk_value: i32,
) -> HttpResponse {
    let sql = format!("DELETE FROM {} WHERE {} = ?", table, pk_field);
    let result = sqlx::query(&sql)
        .bind(pk_value)
        .execute(pool)
        .await;
    match result {
        Ok(_) => HttpResponse::Ok().json(BasicResponse {
            code: 200,
            msg: "删除成功!",
        }),
        Err(e) => {
            eprintln!("数据库删除失败: {:?}", e);
            HttpResponse::InternalServerError().json(BasicResponse {
                code: 500,
                msg: "删除失败!",
            })
        }
    }
}
🍎封装使用删除方法
// 删除用户
pub async fn delete_user(
    pool: web::Data<MySqlPool>, 
    id: web::Path<i32>
) -> HttpResponse {
    crate::common::apimethods::delete_api(
        pool.get_ref(),
        "sys_user",
        "user_id",
        *id
    ).await
}
🍎测试接口ok
{
    "code": 200,
    "msg": "删除成功!"
}
🍎软删除
接下来我们将删除更改为软删除。正常我们项目之中都会有假删除和真删除部分
// 通用删除接口
pub async fn delete_api(
    pool: &MySqlPool,
    table: &str,
    pk_field: &str,
    pk_value: i32,
    soft_delete: bool, // 新增参数,true=软删除,false=真删除
) -> HttpResponse {
    let sql;
    let mut query;
    if soft_delete {
        // 假删除,isDeleted 字段置为 1
        sql = format!("UPDATE {} SET isDeleted = ? WHERE {} = ?", table, pk_field);
        query = sqlx::query(&sql)
            .bind(1) // 1 表示已删除
            .bind(pk_value);
    } else {
        // 真删除
        sql = format!("DELETE FROM {} WHERE {} = ?", table, pk_field);
        query = sqlx::query(&sql)
            .bind(pk_value);
    }
    let result = query.execute(pool).await;
    match result {
        Ok(_) => HttpResponse::Ok().json(BasicResponse {
            code: 200,
            msg: "删除成功!",
        }),
        Err(e) => {
            eprintln!("数据库删除失败: {:?}", e);
            HttpResponse::InternalServerError().json(BasicResponse {
                code: 500,
                msg: "删除失败!",
            })
        }
    }
}
🍎使用软删除
// 软删除
pub async fn delete_user(
    pool: web::Data<MySqlPool>, 
    id: web::Path<i32>
) -> HttpResponse {
    crate::common::apimethods::delete_api(
        pool.get_ref(),
        "sys_user",
        "user_id",
        *id,
        true, // 软删除,isDeleted=1
    ).await
}
🍎使用真删除
// 通用真删除
pub async fn del_delete(
    pool: web::Data<MySqlPool>,
    id: web::Path<i32>
) -> HttpResponse {
    crate::common::apimethods::delete_api(
        pool.get_ref(),
        "sys_user",
        "user_id",
        *id,
        false, // 软删除,isDeleted=1
    ).await
}
            【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
                cloudbbs@huaweicloud.com
                
            
        
        
        
        
        
        
        - 点赞
- 收藏
- 关注作者
 
             
           
评论(0)