axum_sqlx_tx/
config.rs

1use std::marker::PhantomData;
2
3use crate::{Layer, Marker, State};
4
5/// Configuration for [`Tx`](crate::Tx) extractors.
6///
7/// Use `Config` to configure and create a [`State`] and [`Layer`].
8///
9/// Access the `Config` API from [`Tx::config`](crate::Tx::config).
10///
11/// ```
12/// # async fn foo() {
13/// # let pool: sqlx::SqlitePool = todo!();
14/// type Tx = axum_sqlx_tx::Tx<sqlx::Sqlite>;
15///
16/// let config = Tx::config(pool);
17/// # }
18/// ```
19pub struct Config<DB: Marker, LayerError> {
20    pool: sqlx::Pool<DB::Driver>,
21    _layer_error: PhantomData<LayerError>,
22}
23
24impl<DB: Marker, LayerError> Config<DB, LayerError>
25where
26    LayerError: axum_core::response::IntoResponse,
27    sqlx::Error: Into<LayerError>,
28{
29    pub(crate) fn new(pool: sqlx::Pool<DB::Driver>) -> Self {
30        Self {
31            pool,
32            _layer_error: PhantomData,
33        }
34    }
35
36    /// Change the layer error type.
37    pub fn layer_error<E>(self) -> Config<DB, E>
38    where
39        sqlx::Error: Into<E>,
40    {
41        Config {
42            pool: self.pool,
43            _layer_error: PhantomData,
44        }
45    }
46
47    /// Create a [`State`] and [`Layer`] to enable the [`Tx`](crate::Tx) extractor.
48    pub fn setup(self) -> (State<DB>, Layer<DB, LayerError>) {
49        let state = State::new(self.pool);
50        let layer = Layer::new(state.clone());
51        (state, layer)
52    }
53}