feat: provide connection pool to routes
This commit is contained in:
parent
f4deaceb27
commit
68e825c942
5 changed files with 43 additions and 20 deletions
|
|
@ -1,8 +1,11 @@
|
|||
use axum::Form;
|
||||
use axum::http::StatusCode;
|
||||
use axum::extract::State;
|
||||
use axum::routing::post;
|
||||
use axum::Form;
|
||||
use axum::Router;
|
||||
use chrono::Utc;
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct FormData {
|
||||
|
|
@ -10,14 +13,25 @@ struct FormData {
|
|||
name: String,
|
||||
}
|
||||
|
||||
async fn subscribe(Form(params): Form<FormData>) {
|
||||
// println!("Params are: {params:?}");
|
||||
// if params.name.is_empty() || params.email.is_empty() {
|
||||
// return StatusCode::NOT_ACCEPTABLE;
|
||||
// }
|
||||
// StatusCode::OK
|
||||
async fn subscribe(State(pool): State<PgPool>, Form(form): Form<FormData>) {
|
||||
let _ = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO subscriptions (id, email, name, subscribed_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
"#,
|
||||
Uuid::new_v4(),
|
||||
form.email,
|
||||
form.name,
|
||||
Utc::now()
|
||||
)
|
||||
// We use `get_ref` to get an immutable reference to the `PgConnection`
|
||||
// wrapped by `web::Data`.
|
||||
.execute(&pool)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub fn routes_subscriptions() -> Router {
|
||||
Router::new().route("/subscriptions", post(subscribe))
|
||||
pub fn routes_subscriptions(pool: PgPool) -> Router {
|
||||
Router::new()
|
||||
.route("/subscriptions", post(subscribe))
|
||||
.with_state(pool)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,9 +7,8 @@ use tokio::net::TcpListener;
|
|||
/// API routing
|
||||
pub fn app(connection: PgPool) -> Router {
|
||||
Router::new()
|
||||
.with_state(connection)
|
||||
.merge(crate::routes::routes_health_check())
|
||||
.merge(crate::routes::routes_subscriptions())
|
||||
.merge(crate::routes::routes_subscriptions(connection))
|
||||
}
|
||||
|
||||
/// Start the server
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue