创建好数据库连接函数
This commit is contained in:
parent
2111bb54de
commit
969bda1acf
9
.vscode/tasks.json
vendored
9
.vscode/tasks.json
vendored
@ -66,15 +66,6 @@
|
||||
},
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "common-fmt",
|
||||
"type": "shell",
|
||||
"command": "cargo fmt",
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/common"
|
||||
},
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "format-all",
|
||||
"dependsOn": [
|
||||
|
30
server/src/db.rs
Normal file
30
server/src/db.rs
Normal file
@ -0,0 +1,30 @@
|
||||
use surrealdb::{engine::any::{connect,Any}, Surreal,opt::auth::Root};
|
||||
|
||||
use crate::utils::error::CustomResult;
|
||||
|
||||
pub struct Database {
|
||||
client: Surreal<Any>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub async fn new() -> CustomResult<Self> {
|
||||
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<Any> {
|
||||
&self.client
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
@ -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<rocket::Error> for CustomError {
|
||||
}
|
||||
}
|
||||
|
||||
pub type CustomResult<T> = Result<T, CustomError>;
|
||||
impl From<surrealdb::Error> for CustomError {
|
||||
fn from(error: surrealdb::Error) -> Self {
|
||||
CustomError(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub type CustomResult<T> = Result<T, CustomError>;
|
||||
|
Loading…
Reference in New Issue
Block a user