55 lines
1.5 KiB
Rust
55 lines
1.5 KiB
Rust
use axum::{
|
|
async_trait,
|
|
extract::{FromRef, FromRequestParts, State},
|
|
http::{request::Parts, StatusCode},
|
|
};
|
|
use sqlx::SqlitePool;
|
|
|
|
pub async fn using_connection_pool_extractor(
|
|
State(pool): State<SqlitePool>,
|
|
) -> Result<String, (StatusCode, String)> {
|
|
sqlx::query_scalar("select 'hello world from sqlite get'")
|
|
.fetch_one(&pool)
|
|
.await
|
|
.map_err(internal_error)
|
|
}
|
|
|
|
// we can also write a custom extractor that grabs a connection from the pool
|
|
// which setup is appropriate depends on your application
|
|
pub struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Sqlite>);
|
|
|
|
#[async_trait]
|
|
impl<S> FromRequestParts<S> for DatabaseConnection
|
|
where
|
|
SqlitePool: FromRef<S>,
|
|
S: Send + Sync,
|
|
{
|
|
type Rejection = (StatusCode, String);
|
|
|
|
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
|
let pool = SqlitePool::from_ref(state);
|
|
|
|
let conn = pool.acquire().await.map_err(internal_error)?;
|
|
|
|
Ok(Self(conn))
|
|
}
|
|
}
|
|
|
|
pub async fn using_connection_extractor(
|
|
DatabaseConnection(conn): DatabaseConnection,
|
|
) -> Result<String, (StatusCode, String)> {
|
|
let mut conn = conn;
|
|
sqlx::query_scalar("select 'hello world from sqlite post'")
|
|
.fetch_one(&mut conn)
|
|
.await
|
|
.map_err(internal_error)
|
|
}
|
|
|
|
/// Utility function for mapping any error into a `500 Internal Server Error`
|
|
/// response.
|
|
fn internal_error<E>(err: E) -> (StatusCode, String)
|
|
where
|
|
E: std::error::Error,
|
|
{
|
|
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
|
|
}
|