refactor: ♻️ static singleton database connection
This commit is contained in:
parent
b86580f5ba
commit
0dacf1f54f
4 changed files with 12 additions and 15 deletions
|
@ -1,4 +1,4 @@
|
|||
use std::time::Duration;
|
||||
use std::{sync::LazyLock, time::Duration};
|
||||
|
||||
use surrealdb::{
|
||||
engine::remote::ws::{Client, Ws},
|
||||
|
@ -6,13 +6,15 @@ use surrealdb::{
|
|||
};
|
||||
use tokio::time::sleep;
|
||||
|
||||
pub async fn establish_connection() -> Surreal<Client> {
|
||||
Surreal::new::<Ws>("localhost:8000").await.unwrap()
|
||||
static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
|
||||
|
||||
pub async fn establish_connection() -> Result<(), surrealdb::Error> {
|
||||
DB.connect::<Ws>("localhost:8000").await
|
||||
}
|
||||
|
||||
pub async fn is_alive(db: Surreal<Client>) -> bool {
|
||||
pub async fn is_alive() -> bool {
|
||||
tokio::select! {
|
||||
db_result = db.health() => { match db_result {
|
||||
db_result = DB.health() => { match db_result {
|
||||
Ok(_) => true,
|
||||
Err(_) => false,
|
||||
} },
|
||||
|
|
|
@ -1,5 +1,3 @@
|
|||
use surrealdb::{engine::remote::ws::Client, Surreal};
|
||||
|
||||
pub mod database;
|
||||
pub mod http;
|
||||
pub mod package;
|
||||
|
@ -7,6 +5,4 @@ pub mod routing;
|
|||
pub mod utils;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppState {
|
||||
pub db_client: Surreal<Client>,
|
||||
}
|
||||
pub struct AppState {}
|
||||
|
|
|
@ -7,9 +7,8 @@ async fn main() {
|
|||
println!("Hello, world!");
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:2345").await.unwrap();
|
||||
let app_state = AppState {
|
||||
db_client: database::establish_connection().await,
|
||||
};
|
||||
database::establish_connection().await.unwrap();
|
||||
let app_state = AppState {};
|
||||
let router = routing::route(axum::extract::State(app_state)).await;
|
||||
axum::serve(listener, router).await.unwrap();
|
||||
}
|
||||
|
|
|
@ -10,8 +10,8 @@ pub async fn route(State(app_state): State<AppState>) -> Router {
|
|||
.with_state(app_state)
|
||||
}
|
||||
|
||||
async fn alive(State(app_state): State<AppState>) -> impl IntoResponse {
|
||||
let db_status = match database::is_alive(app_state.db_client).await {
|
||||
async fn alive() -> impl IntoResponse {
|
||||
let db_status = match database::is_alive().await {
|
||||
true => "alive",
|
||||
false => "dead",
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue