echoes/backend/src/main.rs

107 lines
3.1 KiB
Rust
Raw Normal View History

// /d:/data/echoes/backend/src/main.rs
/**
* API接口
*
*
* - GET /api/install:
* - GET /api/sql: SQL查询并返回结果
*/
mod config; // 配置模块
mod sql; // SQL模块
use crate::sql::Database; // 引入数据库结构
use once_cell::sync::Lazy; // 用于延迟初始化
use rocket::{get, http::Status, launch, response::status, routes, serde::json::Json}; // 引入Rocket框架相关功能
use std::sync::Arc; // 引入Arc用于线程安全的引用计数
use tokio::sync::Mutex; // 引入Mutex用于异步锁
// 全局数据库连接变量
static DB: Lazy<Arc<Mutex<Option<Database>>>> = Lazy::new(|| Arc::new(Mutex::new(None)));
/**
*
*
* #
* - `database`:
*
* #
* - `Result<(), Box<dyn std::error::Error>>`:
*/
async fn init_db(database: config::Database) -> Result<(), Box<dyn std::error::Error>> {
let database = Database::init(database).await?; // 初始化数据库
*DB.lock().await = Some(database); // 保存数据库实例
2024-11-11 01:38:58 +08:00
Ok(())
}
/**
*
*
* #
* - `Result<Database, Box<dyn std::error::Error>>`:
*/
2024-11-11 01:38:58 +08:00
async fn get_db() -> Result<Database, Box<dyn std::error::Error>> {
DB.lock()
.await
.clone()
.ok_or_else(|| "Database not initialized".into()) // 返回错误信息
}
/**
*
*
* #
* - `Result<Json<Vec<std::collections::HashMap<String, String>>>, status::Custom<String>>`:
*/
#[get("/sql")]
async fn ssql() -> Result<Json<Vec<std::collections::HashMap<String, String>>>, status::Custom<String>> {
2024-11-11 01:38:58 +08:00
let db = get_db().await.map_err(|e| {
status::Custom(
Status::InternalServerError,
format!("Database error: {}", e), // 数据库错误信息
)
2024-11-11 01:38:58 +08:00
})?;
let query_result = db
.get_db()
.query("SELECT * FROM info".to_string())
2024-11-11 01:38:58 +08:00
.await
.map_err(|e| status::Custom(Status::InternalServerError, format!("Query error: {}", e)))?;
2024-11-11 01:38:58 +08:00
Ok(Json(query_result)) // 返回查询结果
}
/**
*
*
* #
* - `status::Custom<String>`:
*/
2024-11-11 01:38:58 +08:00
#[get("/install")]
async fn install() -> status::Custom<String> {
get_db()
.await
.map(|_| status::Custom(Status::Ok, "Database connected successfully".into())) // 连接成功
.unwrap_or_else(|e| {
status::Custom(
Status::InternalServerError,
format!("Failed to connect: {}", e), // 连接失败信息
)
})
2024-11-11 01:38:58 +08:00
}
/**
* Rocket应用
*
* #
* - `rocket::Rocket`: Rocket实例
*/
#[launch]
async fn rocket() -> _ {
let config = config::Config::read("./src/config/config.toml").expect("Failed to read config"); // 读取配置
init_db(config.database)
.await
.expect("Failed to connect to database"); // 初始化数据库连接
rocket::build().mount("/api", routes![install, ssql]) // 挂载API路由
}