diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 77cacb4..1fcba49 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -66,15 +66,6 @@ }, "problemMatcher": [] }, - { - "label": "common-fmt", - "type": "shell", - "command": "cargo fmt", - "options": { - "cwd": "${workspaceFolder}/common" - }, - "problemMatcher": [] - }, { "label": "format-all", "dependsOn": [ diff --git a/server/src/db.rs b/server/src/db.rs new file mode 100644 index 0000000..825a07a --- /dev/null +++ b/server/src/db.rs @@ -0,0 +1,30 @@ +use surrealdb::{engine::any::{connect,Any}, Surreal,opt::auth::Root}; + +use crate::utils::error::CustomResult; + +pub struct Database { + client: Surreal, +} + +impl Database { + pub async fn new() -> CustomResult { + let client = connect("ws://172.30.113.67:5000").await?; + + // 使用root账户进行认证 + client + .signin(Root { + username: "root", + password: "root", + }) + .await?; + + // 选择命名空间和数据库 + client.use_ns("test").use_db("test").await?; + + Ok(Self { client }) + } + + pub fn get_client(&self) -> &Surreal { + &self.client + } +} diff --git a/server/src/main.rs b/server/src/main.rs index 4d065b8..20edf0d 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -1,10 +1,13 @@ +mod db; mod utils; -use rocket::{get, routes}; -use surrealdb; + +use db::Database; +use rocket::{get, routes, State}; +use serde::{Deserialize, Serialize}; +use std::sync::{Arc, Mutex}; + use utils::error::CustomResult; - - #[get("/")] fn index() -> &'static str { "Hello, world!" @@ -15,17 +18,21 @@ fn get_theme() -> &'static str { "light" } -struct Appstate{ - +pub struct AppState { + db: Database, } #[rocket::main] async fn main() -> CustomResult<()> { let rocket_build = rocket::build(); + let db = Database::new().await?; + let rocket = rocket_build .mount("/", routes![index, get_theme]) - .ignite().await?; + .manage(AppState { db }) + .ignite() + .await?; rocket.launch().await?; std::process::exit(0); -} \ No newline at end of file +} diff --git a/server/src/utils/error.rs b/server/src/utils/error.rs index 2b842ff..0206f5c 100644 --- a/server/src/utils/error.rs +++ b/server/src/utils/error.rs @@ -1,5 +1,6 @@ use common::error::CommonError; use rocket; +use surrealdb; #[derive(Debug)] pub struct CustomError(pub String); @@ -26,5 +27,10 @@ impl From for CustomError { } } -pub type CustomResult = Result; +impl From for CustomError { + fn from(error: surrealdb::Error) -> Self { + CustomError(error.to_string()) + } +} +pub type CustomResult = Result;