Skip to content

Commit

Permalink
Add database health check for ping handler
Browse files Browse the repository at this point in the history
Signed-off-by: JmPotato <[email protected]>
  • Loading branch information
JmPotato committed Sep 29, 2024
1 parent e7a1bbf commit e43c7b1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,20 @@ pub async fn handler_delete_post<T: Editable>(
.into_response()
}

pub async fn handler_ping() -> impl IntoResponse {
"pong"
pub async fn handler_ping(State(state): State<Arc<AppState>>) -> impl IntoResponse {
// Check if the database connection is alive.
if state.db.is_closed() {
return (
StatusCode::INTERNAL_SERVER_ERROR,
"Database connection is closed".to_string(),
);
}
// Check if the database read can be performed.
if let Err(err) = User::try_check_initialization(&state.db).await {
return (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to read from the database: {:?}", err),
);
}
(StatusCode::OK, "pong".to_string())
}
8 changes: 8 additions & 0 deletions src/models/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,12 @@ impl User {
.await?;
Ok(())
}

pub async fn try_check_initialization(db: &sqlx::MySqlPool) -> Result<(), Error> {
sqlx::query("SELECT * FROM users LIMIT 1")
.fetch_one(db)
.await
.map_err(|e| e.into())
.map(|_| ())
}
}

0 comments on commit e43c7b1

Please sign in to comment.