diff --git a/src/database.rs b/src/database.rs index d42c87d..2de4d2e 100644 --- a/src/database.rs +++ b/src/database.rs @@ -9,17 +9,19 @@ pub mod role; pub mod user; pub mod user_contact; -use std::time::Duration; +use std::{sync::LazyLock, time::Duration}; use sqlx::{postgres::PgPoolOptions, Connection, Pool, Postgres}; use tokio::time::sleep; use crate::DatabaseConfig; +static DATABASE_CONNECTIONS: LazyLock> = LazyLock::new(establish_connection); + pub async fn set_database_up(database_connection: &Pool) { sqlx::migrate!().run(database_connection).await.unwrap(); } -pub async fn establish_connection() -> Pool { +pub fn establish_connection() -> Pool { let database_config = DatabaseConfig::default(); let connection_string = format!( "{}://{}:{}@{}/{}", @@ -32,14 +34,13 @@ pub async fn establish_connection() -> Pool { PgPoolOptions::new() .max_connections(database_config.connection_pool_size) .test_before_acquire(false) - .connect(&connection_string) - .await + .connect_lazy(&connection_string) .unwrap() } -pub async fn is_alive(database_connection: &Pool) -> bool { +pub async fn is_alive() -> bool { tokio::select! { - database_connection = database_connection.acquire() => { + database_connection = DATABASE_CONNECTIONS.acquire() => { match database_connection { Ok(mut database_connection) => { match database_connection.ping().await { diff --git a/src/database/comment.rs b/src/database/comment.rs index cd01e1c..260577d 100644 --- a/src/database/comment.rs +++ b/src/database/comment.rs @@ -1,33 +1,30 @@ use chrono::{DateTime, Utc}; -use sqlx::{Pool, Postgres}; use crate::feature::comment::Comment; +use super::DATABASE_CONNECTIONS; + pub async fn create( post_creation_time: &DateTime, user_id: &i64, comment: &String, - database_connection: &Pool, ) -> Result { sqlx::query_as!( Comment, r#" - INSERT INTO "comment"(post_creation_time, user_id, comment) - VALUES ($1, $2, $3) + INSERT INTO "comment"(post_creation_time, user_id, comment) + VALUES ($1, $2, $3) RETURNING * "#, post_creation_time, user_id, comment, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - creation_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn read(creation_time: &DateTime) -> Result { sqlx::query_as!( Comment, r#" @@ -35,14 +32,13 @@ pub async fn read( "#, creation_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } pub async fn update( creation_time: &DateTime, comment: &String, - database_connection: &Pool, ) -> Result { sqlx::query_as!( Comment, @@ -53,14 +49,11 @@ pub async fn update( creation_time, comment ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - creation_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn delete(creation_time: &DateTime) -> Result { sqlx::query_as!( Comment, r#" @@ -69,13 +62,12 @@ pub async fn delete( "#, creation_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } pub async fn read_all_for_post( post_creation_time: &DateTime, - database_connection: &Pool, ) -> Result, sqlx::Error> { sqlx::query_as!( Comment, @@ -84,6 +76,6 @@ pub async fn read_all_for_post( "#, post_creation_time ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/comment_interaction.rs b/src/database/comment_interaction.rs index c5c1baa..a38e745 100644 --- a/src/database/comment_interaction.rs +++ b/src/database/comment_interaction.rs @@ -1,33 +1,30 @@ use chrono::{DateTime, Utc}; -use sqlx::{Pool, Postgres}; use crate::feature::comment_interaction::CommentInteraction; +use super::DATABASE_CONNECTIONS; + pub async fn create( comment_creation_time: &DateTime, user_id: &i64, interaction_id: &i64, - database_connection: &Pool, ) -> Result { sqlx::query_as!( CommentInteraction, r#" - INSERT INTO "comment_interaction"(comment_creation_time, user_id, interaction_id) - VALUES ($1, $2, $3) + INSERT INTO "comment_interaction"(comment_creation_time, user_id, interaction_id) + VALUES ($1, $2, $3) RETURNING * "#, comment_creation_time, user_id, interaction_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - interaction_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn read(interaction_time: &DateTime) -> Result { sqlx::query_as!( CommentInteraction, r#" @@ -35,14 +32,13 @@ pub async fn read( "#, interaction_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } pub async fn update( interaction_time: &DateTime, interaction_id: &i64, - database_connection: &Pool, ) -> Result { sqlx::query_as!( CommentInteraction, @@ -53,14 +49,11 @@ pub async fn update( interaction_time, interaction_id ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - interaction_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn delete(interaction_time: &DateTime) -> Result { sqlx::query_as!( CommentInteraction, r#" @@ -69,13 +62,12 @@ pub async fn delete( "#, interaction_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } pub async fn read_all_for_comment( comment_creation_time: &DateTime, - database_connection: &Pool, ) -> Result, sqlx::Error> { sqlx::query_as!( CommentInteraction, @@ -84,6 +76,6 @@ pub async fn read_all_for_comment( "#, comment_creation_time ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/contact.rs b/src/database/contact.rs index 1971515..68e498a 100644 --- a/src/database/contact.rs +++ b/src/database/contact.rs @@ -1,25 +1,22 @@ -use sqlx::{Pool, Postgres}; - use crate::feature::contact::Contact; -pub async fn create( - name: &String, - database_connection: &Pool, -) -> Result { +use super::DATABASE_CONNECTIONS; + +pub async fn create(name: &String) -> Result { sqlx::query_as!( Contact, r#" - INSERT INTO "contact"(name) - VALUES ($1) + INSERT INTO "contact"(name) + VALUES ($1) RETURNING * "#, name, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read(id: &i64, database_connection: &Pool) -> Result { +pub async fn read(id: &i64) -> Result { sqlx::query_as!( Contact, r#" @@ -27,15 +24,11 @@ pub async fn read(id: &i64, database_connection: &Pool) -> Result, -) -> Result { +pub async fn update(id: &i64, name: &String) -> Result { sqlx::query_as!( Contact, r#" @@ -45,14 +38,11 @@ pub async fn update( id, name, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn delete(id: &i64) -> Result { sqlx::query_as!( Contact, r#" @@ -61,17 +51,17 @@ pub async fn delete( "#, id ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all(database_connection: &Pool) -> Result, sqlx::Error> { +pub async fn read_all() -> Result, sqlx::Error> { sqlx::query_as!( Contact, r#" SELECT * FROM "contact" "#, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/interaction.rs b/src/database/interaction.rs index 3e41d64..3eedfbe 100644 --- a/src/database/interaction.rs +++ b/src/database/interaction.rs @@ -1,28 +1,22 @@ -use sqlx::{Pool, Postgres}; - use crate::feature::interaction::Interaction; -pub async fn create( - name: &String, - database_connection: &Pool, -) -> Result { +use super::DATABASE_CONNECTIONS; + +pub async fn create(name: &String) -> Result { sqlx::query_as!( Interaction, r#" - INSERT INTO "interaction"(name) - VALUES ($1) + INSERT INTO "interaction"(name) + VALUES ($1) RETURNING * "#, name, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn read(id: &i64) -> Result { sqlx::query_as!( Interaction, r#" @@ -30,15 +24,11 @@ pub async fn read( "#, id ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn update( - id: &i64, - name: &String, - database_connection: &Pool, -) -> Result { +pub async fn update(id: &i64, name: &String) -> Result { sqlx::query_as!( Interaction, r#" @@ -48,14 +38,11 @@ pub async fn update( id, name ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn delete(id: &i64) -> Result { sqlx::query_as!( Interaction, r#" @@ -64,19 +51,17 @@ pub async fn delete( "#, id ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all( - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all() -> Result, sqlx::Error> { sqlx::query_as!( Interaction, r#" SELECT * FROM "interaction" "#, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/login.rs b/src/database/login.rs index ca54cfb..a87e187 100644 --- a/src/database/login.rs +++ b/src/database/login.rs @@ -1,12 +1,8 @@ -use sqlx::{Pool, Postgres}; - use crate::feature::login::Login; -pub async fn create( - user_id: &i64, - token: &String, - database_connection: &Pool, -) -> Result { +use super::DATABASE_CONNECTIONS; + +pub async fn create(user_id: &i64, token: &String) -> Result { sqlx::query_as!( Login, r#" @@ -17,15 +13,11 @@ pub async fn create( user_id, token, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - user_id: &i64, - token: &String, - database_connection: &Pool, -) -> Result { +pub async fn read(user_id: &i64, token: &String) -> Result { sqlx::query_as!( Login, r#" @@ -34,15 +26,11 @@ pub async fn read( user_id, token ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - user_id: &i64, - token: &String, - database_connection: &Pool, -) -> Result { +pub async fn delete(user_id: &i64, token: &String) -> Result { sqlx::query_as!( Login, r#" @@ -52,14 +40,11 @@ pub async fn delete( user_id, token, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_user( - user_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_user(user_id: &i64) -> Result, sqlx::Error> { sqlx::query_as!( Login, r#" @@ -67,14 +52,11 @@ pub async fn read_all_for_user( "#, user_id, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn delete_all_for_user( - user_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn delete_all_for_user(user_id: &i64) -> Result, sqlx::Error> { sqlx::query_as!( Login, r#" @@ -83,21 +65,18 @@ pub async fn delete_all_for_user( "#, user_id, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn count_all_for_user( - user_id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn count_all_for_user(user_id: &i64) -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "login" WHERE "user_id" = $1 "#, user_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) diff --git a/src/database/post.rs b/src/database/post.rs index 498d434..f6d1f35 100644 --- a/src/database/post.rs +++ b/src/database/post.rs @@ -1,31 +1,25 @@ use chrono::{DateTime, Utc}; -use sqlx::{Pool, Postgres}; use crate::feature::post::Post; -pub async fn create( - user_id: &i64, - post: &String, - database_connection: &Pool, -) -> Result { +use super::DATABASE_CONNECTIONS; + +pub async fn create(user_id: &i64, post: &String) -> Result { sqlx::query_as!( Post, r#" - INSERT INTO "post"(user_id, post) - VALUES ($1, $2) + INSERT INTO "post"(user_id, post) + VALUES ($1, $2) RETURNING * "#, user_id, post ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - creation_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn read(creation_time: &DateTime) -> Result { sqlx::query_as!( Post, r#" @@ -33,7 +27,7 @@ pub async fn read( "#, creation_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } @@ -41,7 +35,6 @@ pub async fn update( creation_time: &DateTime, user_id: &i64, post: &String, - database_connection: &Pool, ) -> Result { sqlx::query_as!( Post, @@ -53,14 +46,11 @@ pub async fn update( user_id, post ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - creation_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn delete(creation_time: &DateTime) -> Result { sqlx::query_as!( Post, r#" @@ -69,25 +59,22 @@ pub async fn delete( "#, creation_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all(database_connection: &Pool) -> Result, sqlx::Error> { +pub async fn read_all() -> Result, sqlx::Error> { sqlx::query_as!( Post, r#" SELECT * FROM "post" "#, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_user( - user_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_user(user_id: &i64) -> Result, sqlx::Error> { sqlx::query_as!( Post, r#" @@ -95,6 +82,6 @@ pub async fn read_all_for_user( "#, user_id ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/post_interaction.rs b/src/database/post_interaction.rs index 2c7b90d..87c57f7 100644 --- a/src/database/post_interaction.rs +++ b/src/database/post_interaction.rs @@ -1,33 +1,30 @@ use chrono::{DateTime, Utc}; -use sqlx::{Pool, Postgres}; use crate::feature::post_interaction::PostInteraction; +use super::DATABASE_CONNECTIONS; + pub async fn create( post_creation_time: &DateTime, user_id: &i64, interaction_id: &i64, - database_connection: &Pool, ) -> Result { sqlx::query_as!( PostInteraction, r#" - INSERT INTO "post_interaction"(post_creation_time, user_id, interaction_id) - VALUES ($1, $2, $3) + INSERT INTO "post_interaction"(post_creation_time, user_id, interaction_id) + VALUES ($1, $2, $3) RETURNING * "#, post_creation_time, user_id, interaction_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - interaction_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn read(interaction_time: &DateTime) -> Result { sqlx::query_as!( PostInteraction, r#" @@ -35,14 +32,13 @@ pub async fn read( "#, interaction_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } pub async fn update( interaction_time: &DateTime, interaction_id: &i64, - database_connection: &Pool, ) -> Result { sqlx::query_as!( PostInteraction, @@ -53,14 +49,11 @@ pub async fn update( interaction_time, interaction_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - interaction_time: &DateTime, - database_connection: &Pool, -) -> Result { +pub async fn delete(interaction_time: &DateTime) -> Result { sqlx::query_as!( PostInteraction, r#" @@ -69,13 +62,12 @@ pub async fn delete( "#, interaction_time ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } pub async fn read_all_for_post( post_creation_time: &DateTime, - database_connection: &Pool, ) -> Result, sqlx::Error> { sqlx::query_as!( PostInteraction, @@ -84,6 +76,6 @@ pub async fn read_all_for_post( "#, post_creation_time ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/role.rs b/src/database/role.rs index c12729d..048cf5f 100644 --- a/src/database/role.rs +++ b/src/database/role.rs @@ -1,25 +1,22 @@ -use sqlx::{Pool, Postgres}; - use crate::feature::role::Role; -pub async fn create( - name: &String, - database_connection: &Pool, -) -> Result { +use super::DATABASE_CONNECTIONS; + +pub async fn create(name: &String) -> Result { sqlx::query_as!( Role, r#" - INSERT INTO "role"(name) - VALUES ($1) + INSERT INTO "role"(name) + VALUES ($1) RETURNING * "#, name, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read(id: &i64, database_connection: &Pool) -> Result { +pub async fn read(id: &i64) -> Result { sqlx::query_as!( Role, r#" @@ -27,15 +24,11 @@ pub async fn read(id: &i64, database_connection: &Pool) -> Result, -) -> Result { +pub async fn update(id: &i64, name: &String) -> Result { sqlx::query_as!( Role, r#" @@ -45,11 +38,11 @@ pub async fn update( id, name, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete(id: &i64, database_connection: &Pool) -> Result { +pub async fn delete(id: &i64) -> Result { sqlx::query_as!( Role, r#" @@ -58,17 +51,17 @@ pub async fn delete(id: &i64, database_connection: &Pool) -> Result) -> Result, sqlx::Error> { +pub async fn read_all() -> Result, sqlx::Error> { sqlx::query_as!( Role, r#" SELECT * FROM "role" "#, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/database/user.rs b/src/database/user.rs index 9099cc8..0b95b9d 100644 --- a/src/database/user.rs +++ b/src/database/user.rs @@ -1,14 +1,14 @@ use chrono::NaiveDate; -use sqlx::{Pool, Postgres}; use crate::feature::user::User; +use super::DATABASE_CONNECTIONS; + pub async fn create( name: &String, surname: &String, gender: &bool, birth_date: &NaiveDate, - database_connection: &Pool, ) -> Result { sqlx::query_as!( User, @@ -23,11 +23,11 @@ pub async fn create( birth_date, 2 ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read(id: &i64, database_connection: &Pool) -> Result { +pub async fn read(id: &i64) -> Result { sqlx::query_as!( User, r#" @@ -35,7 +35,7 @@ pub async fn read(id: &i64, database_connection: &Pool) -> Result, ) -> Result { sqlx::query_as!(User, r#" UPDATE "user" SET "name" = $2, "surname" = $3, "gender" = $4, "birth_date" = $5, "role_id" = $6 WHERE "user_id" = $1 RETURNING * - "#, id, name, surname, gender, birth_date, role_id).fetch_one(database_connection).await + "#, id, name, surname, gender, birth_date, role_id).fetch_one(&*DATABASE_CONNECTIONS).await } -pub async fn delete(id: &i64, database_connection: &Pool) -> Result { +pub async fn delete(id: &i64) -> Result { sqlx::query_as!( User, r#" @@ -64,25 +63,22 @@ pub async fn delete(id: &i64, database_connection: &Pool) -> Result) -> Result, sqlx::Error> { +pub async fn read_all() -> Result, sqlx::Error> { sqlx::query_as!( User, r#" SELECT * FROM "user" "#, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_name( - name: &String, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_name(name: &String) -> Result, sqlx::Error> { sqlx::query_as!( User, r#" @@ -90,14 +86,11 @@ pub async fn read_all_for_name( "#, name ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_surname( - surname: &String, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_surname(surname: &String) -> Result, sqlx::Error> { sqlx::query_as!( User, r#" @@ -105,14 +98,11 @@ pub async fn read_all_for_surname( "#, surname ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_birth_date( - birth_date: &NaiveDate, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_birth_date(birth_date: &NaiveDate) -> Result, sqlx::Error> { sqlx::query_as!( User, r#" @@ -120,14 +110,11 @@ pub async fn read_all_for_birth_date( "#, birth_date ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_role( - role_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_role(role_id: &i64) -> Result, sqlx::Error> { sqlx::query_as!( User, r#" @@ -135,14 +122,11 @@ pub async fn read_all_for_role( "#, role_id ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_gender( - gender: &bool, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_gender(gender: &bool) -> Result, sqlx::Error> { sqlx::query_as!( User, r#" @@ -150,115 +134,100 @@ pub async fn read_all_for_gender( "#, gender ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_id(database_connection: &Pool) -> Result, sqlx::Error> { +pub async fn read_all_id() -> Result, sqlx::Error> { Ok(sqlx::query!( r#" SELECT "user_id" FROM "user" "#, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await? .iter() .map(|record| record.user_id) .collect::>()) } -pub async fn read_all_id_for_name( - name: &String, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_id_for_name(name: &String) -> Result, sqlx::Error> { Ok(sqlx::query!( r#" SELECT "user_id" FROM "user" WHERE "name" = $1 "#, name ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await? .iter() .map(|record| record.user_id) .collect::>()) } -pub async fn read_all_id_for_surname( - surname: &String, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_id_for_surname(surname: &String) -> Result, sqlx::Error> { Ok(sqlx::query!( r#" SELECT "user_id" FROM "user" WHERE "surname" = $1 "#, surname ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await? .iter() .map(|record| record.user_id) .collect::>()) } -pub async fn read_all_id_for_birth_date( - birth_date: &NaiveDate, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_id_for_birth_date(birth_date: &NaiveDate) -> Result, sqlx::Error> { Ok(sqlx::query!( r#" SELECT "user_id" FROM "user" WHERE "birth_date" = $1 "#, birth_date ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await? .iter() .map(|record| record.user_id) .collect::>()) } -pub async fn read_all_id_for_role( - role_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_id_for_role(role_id: &i64) -> Result, sqlx::Error> { Ok(sqlx::query!( r#" SELECT "user_id" FROM "user" WHERE "role_id" = $1 "#, role_id ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await? .iter() .map(|record| record.user_id) .collect::>()) } -pub async fn read_all_id_for_gender( - gender: &bool, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_id_for_gender(gender: &bool) -> Result, sqlx::Error> { Ok(sqlx::query!( r#" SELECT "user_id" FROM "user" WHERE "gender" = $1 "#, gender ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await? .iter() .map(|record| record.user_id) .collect::>()) } -pub async fn count_all(database_connection: &Pool) -> Result { +pub async fn count_all() -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "user" "#, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) @@ -266,17 +235,14 @@ pub async fn count_all(database_connection: &Pool) -> Result, -) -> Result { +pub async fn count_all_for_name(name: &String) -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "user" WHERE "name" = $1 "#, name ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) @@ -284,17 +250,14 @@ pub async fn count_all_for_name( .or(Ok(0)) } -pub async fn count_all_for_surname( - surname: &String, - database_connection: &Pool, -) -> Result { +pub async fn count_all_for_surname(surname: &String) -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "user" WHERE "surname" = $1 "#, surname ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) @@ -302,17 +265,14 @@ pub async fn count_all_for_surname( .or(Ok(0)) } -pub async fn count_all_for_birth_date( - birth_date: &NaiveDate, - database_connection: &Pool, -) -> Result { +pub async fn count_all_for_birth_date(birth_date: &NaiveDate) -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "user" WHERE "birth_date" = $1 "#, birth_date ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) @@ -320,17 +280,14 @@ pub async fn count_all_for_birth_date( .or(Ok(0)) } -pub async fn count_all_for_role( - role_id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn count_all_for_role(role_id: &i64) -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "user" WHERE "role_id" = $1 "#, role_id ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) @@ -338,17 +295,14 @@ pub async fn count_all_for_role( .or(Ok(0)) } -pub async fn count_all_for_gender( - gender: &bool, - database_connection: &Pool, -) -> Result { +pub async fn count_all_for_gender(gender: &bool) -> Result { sqlx::query!( r#" SELECT COUNT(user_id) FROM "user" WHERE "gender" = $1 "#, gender ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await? .count .map_or(0, |count| count) diff --git a/src/database/user_contact.rs b/src/database/user_contact.rs index e094118..e6d908f 100644 --- a/src/database/user_contact.rs +++ b/src/database/user_contact.rs @@ -1,31 +1,23 @@ -use sqlx::{Pool, Postgres}; - use crate::feature::user_contact::UserContact; -pub async fn create( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, -) -> Result { +use super::DATABASE_CONNECTIONS; + +pub async fn create(user_id: &i64, contact_id: &i64) -> Result { sqlx::query_as!( UserContact, r#" - INSERT INTO "user_contact"(user_id, contact_id) - VALUES ($1, $2) + INSERT INTO "user_contact"(user_id, contact_id) + VALUES ($1, $2) RETURNING * "#, user_id, contact_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn read(user_id: &i64, contact_id: &i64) -> Result { sqlx::query_as!( UserContact, r#" @@ -34,15 +26,11 @@ pub async fn read( user_id, contact_id ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn update( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn update(user_id: &i64, contact_id: &i64) -> Result { sqlx::query_as!( UserContact, r#" @@ -52,15 +40,11 @@ pub async fn update( user_id, contact_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn delete( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, -) -> Result { +pub async fn delete(user_id: &i64, contact_id: &i64) -> Result { sqlx::query_as!( UserContact, r#" @@ -70,14 +54,11 @@ pub async fn delete( user_id, contact_id, ) - .fetch_one(database_connection) + .fetch_one(&*DATABASE_CONNECTIONS) .await } -pub async fn read_all_for_user( - user_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn read_all_for_user(user_id: &i64) -> Result, sqlx::Error> { sqlx::query_as!( UserContact, r#" @@ -85,14 +66,11 @@ pub async fn read_all_for_user( "#, user_id, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } -pub async fn delete_all_for_user( - user_id: &i64, - database_connection: &Pool, -) -> Result, sqlx::Error> { +pub async fn delete_all_for_user(user_id: &i64) -> Result, sqlx::Error> { sqlx::query_as!( UserContact, r#" @@ -101,6 +79,6 @@ pub async fn delete_all_for_user( "#, user_id, ) - .fetch_all(database_connection) + .fetch_all(&*DATABASE_CONNECTIONS) .await } diff --git a/src/feature/auth.rs b/src/feature/auth.rs index 009e078..b751db3 100644 --- a/src/feature/auth.rs +++ b/src/feature/auth.rs @@ -1,14 +1,18 @@ +use std::sync::LazyLock; + use serde::{Deserialize, Serialize}; use tokio::sync::RwLock; use crate::{ error::ForumMailError, mail::{MailFieldsOneTimePassword, MailTemplate}, - ONE_TIME_PASSWORDS, }; use super::user::User; +static ONE_TIME_PASSWORDS: LazyLock>> = + LazyLock::new(OneTimePassword::init); + #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct OneTimePassword { pub user_id: i64, diff --git a/src/feature/comment.rs b/src/feature/comment.rs index 4b43dd8..c533e3c 100644 --- a/src/feature/comment.rs +++ b/src/feature/comment.rs @@ -1,6 +1,5 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::comment; @@ -17,37 +16,28 @@ impl Comment { post_creation_time: &DateTime, user_id: &i64, comment: &String, - database_connection: &Pool, ) -> Result { - comment::create(post_creation_time, user_id, comment, database_connection).await + comment::create(post_creation_time, user_id, comment).await } - pub async fn read( - creation_time: &DateTime, - database_connection: &Pool, - ) -> Result { - comment::read(creation_time, database_connection).await + pub async fn read(creation_time: &DateTime) -> Result { + comment::read(creation_time).await } pub async fn update( creation_time: &DateTime, comment: &String, - database_connection: &Pool, ) -> Result { - comment::update(creation_time, comment, database_connection).await + comment::update(creation_time, comment).await } - pub async fn delete( - creation_time: &DateTime, - database_connection: &Pool, - ) -> Result { - comment::delete(creation_time, database_connection).await + pub async fn delete(creation_time: &DateTime) -> Result { + comment::delete(creation_time).await } pub async fn read_all_for_post( post_creation_time: &DateTime, - database_connection: &Pool, ) -> Result, sqlx::Error> { - comment::read_all_for_post(post_creation_time, database_connection).await + comment::read_all_for_post(post_creation_time).await } } diff --git a/src/feature/comment_interaction.rs b/src/feature/comment_interaction.rs index e97d773..e9c8e04 100644 --- a/src/feature/comment_interaction.rs +++ b/src/feature/comment_interaction.rs @@ -1,6 +1,5 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::comment_interaction; @@ -17,43 +16,30 @@ impl CommentInteraction { comment_creation_time: &DateTime, user_id: &i64, interaction_id: &i64, - database_connection: &Pool, ) -> Result { - comment_interaction::create( - comment_creation_time, - user_id, - interaction_id, - database_connection, - ) - .await + comment_interaction::create(comment_creation_time, user_id, interaction_id).await } - pub async fn read( - interaction_time: &DateTime, - database_connection: &Pool, - ) -> Result { - comment_interaction::read(interaction_time, database_connection).await + pub async fn read(interaction_time: &DateTime) -> Result { + comment_interaction::read(interaction_time).await } pub async fn update( interaction_time: &DateTime, interaction_id: &i64, - database_connection: &Pool, ) -> Result { - comment_interaction::update(interaction_time, interaction_id, database_connection).await + comment_interaction::update(interaction_time, interaction_id).await } pub async fn delete( interaction_time: &DateTime, - database_connection: &Pool, ) -> Result { - comment_interaction::delete(interaction_time, database_connection).await + comment_interaction::delete(interaction_time).await } pub async fn read_all_for_comment( comment_creation_time: &DateTime, - database_connection: &Pool, ) -> Result, sqlx::Error> { - comment_interaction::read_all_for_comment(comment_creation_time, database_connection).await + comment_interaction::read_all_for_comment(comment_creation_time).await } } diff --git a/src/feature/contact.rs b/src/feature/contact.rs index d3a92f2..bfffbe8 100644 --- a/src/feature/contact.rs +++ b/src/feature/contact.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::contact; @@ -10,38 +9,23 @@ pub struct Contact { } impl Contact { - pub async fn create( - name: &String, - database_connection: &Pool, - ) -> Result { - contact::create(name, database_connection).await + pub async fn create(name: &String) -> Result { + contact::create(name).await } - pub async fn read( - id: &i64, - database_connection: &Pool, - ) -> Result { - contact::read(id, database_connection).await + pub async fn read(id: &i64) -> Result { + contact::read(id).await } - pub async fn update( - id: &i64, - name: &String, - database_connection: &Pool, - ) -> Result { - contact::update(id, name, database_connection).await + pub async fn update(id: &i64, name: &String) -> Result { + contact::update(id, name).await } - pub async fn delete( - id: &i64, - database_connection: &Pool, - ) -> Result { - contact::delete(id, database_connection).await + pub async fn delete(id: &i64) -> Result { + contact::delete(id).await } - pub async fn read_all( - database_connection: &Pool, - ) -> Result, sqlx::Error> { - contact::read_all(database_connection).await + pub async fn read_all() -> Result, sqlx::Error> { + contact::read_all().await } } diff --git a/src/feature/interaction.rs b/src/feature/interaction.rs index e5c4cf8..2e259b5 100644 --- a/src/feature/interaction.rs +++ b/src/feature/interaction.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::interaction; @@ -10,38 +9,23 @@ pub struct Interaction { } impl Interaction { - pub async fn create( - name: &String, - database_connection: &Pool, - ) -> Result { - interaction::create(name, database_connection).await + pub async fn create(name: &String) -> Result { + interaction::create(name).await } - pub async fn read( - id: &i64, - database_connection: &Pool, - ) -> Result { - interaction::read(id, database_connection).await + pub async fn read(id: &i64) -> Result { + interaction::read(id).await } - pub async fn update( - id: &i64, - name: &String, - database_connection: &Pool, - ) -> Result { - interaction::update(id, name, database_connection).await + pub async fn update(id: &i64, name: &String) -> Result { + interaction::update(id, name).await } - pub async fn delete( - id: &i64, - database_connection: &Pool, - ) -> Result { - interaction::delete(id, database_connection).await + pub async fn delete(id: &i64) -> Result { + interaction::delete(id).await } - pub async fn read_all( - database_connection: &Pool, - ) -> Result, sqlx::Error> { - interaction::read_all(database_connection).await + pub async fn read_all() -> Result, sqlx::Error> { + interaction::read_all().await } } diff --git a/src/feature/login.rs b/src/feature/login.rs index 12329a4..069c930 100644 --- a/src/feature/login.rs +++ b/src/feature/login.rs @@ -7,7 +7,6 @@ use jwt_simple::{ prelude::{HS256Key, MACLike}, }; use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::{database::login, error::ForumAuthError, SERVER_CONFIG}; @@ -65,34 +64,26 @@ pub struct Login { } impl Login { - pub async fn create( - user_id: &i64, - database_connection: &Pool, - ) -> Result { - User::read(user_id, database_connection).await?; + pub async fn create(user_id: &i64) -> Result { + User::read(user_id).await?; let token = TokenMeta::create_token(user_id) .await .expect("Should not panic if it isn't configured wrong"); - login::create(user_id, &token, database_connection).await + login::create(user_id, &token).await } - pub async fn read( - user_id: &i64, - token: &String, - database_connection: &Pool, - ) -> Result { - User::read(user_id, database_connection).await?; + pub async fn read(user_id: &i64, token: &String) -> Result { + User::read(user_id).await?; - login::read(user_id, token, database_connection).await + login::read(user_id, token).await } pub async fn update( user_id: &i64, token: &String, - database_connection: &Pool, ) -> Result> { - let login = Login::read(user_id, token, database_connection).await?; + let login = Login::read(user_id, token).await?; match TokenMeta::verify_token(token).await { Ok(_) => Ok(login), Err(_) => { @@ -101,8 +92,8 @@ impl Login { .num_minutes() <= SERVER_CONFIG.login_token_refresh_time_limit as i64 { - Login::delete(user_id, token, database_connection).await?; - let login = Login::create(user_id, database_connection).await?; + Login::delete(user_id, token).await?; + let login = Login::create(user_id).await?; Ok(login) } else { Err(Box::new(ForumAuthError::TokenRefreshTimeOver)) @@ -110,32 +101,19 @@ impl Login { } } } - pub async fn delete( - user_id: &i64, - token: &String, - database_connection: &Pool, - ) -> Result { - login::delete(user_id, token, database_connection).await + pub async fn delete(user_id: &i64, token: &String) -> Result { + login::delete(user_id, token).await } - pub async fn read_all_for_user( - user_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - login::read_all_for_user(user_id, database_connection).await + pub async fn read_all_for_user(user_id: &i64) -> Result, sqlx::Error> { + login::read_all_for_user(user_id).await } - pub async fn delete_all_for_user( - user_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - login::delete_all_for_user(user_id, database_connection).await + pub async fn delete_all_for_user(user_id: &i64) -> Result, sqlx::Error> { + login::delete_all_for_user(user_id).await } - pub async fn count_all_for_user( - user_id: &i64, - database_connection: &Pool, - ) -> Result { - login::count_all_for_user(user_id, database_connection).await + pub async fn count_all_for_user(user_id: &i64) -> Result { + login::count_all_for_user(user_id).await } } diff --git a/src/feature/post.rs b/src/feature/post.rs index f41255d..23e68c4 100644 --- a/src/feature/post.rs +++ b/src/feature/post.rs @@ -1,6 +1,5 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::post; @@ -12,45 +11,31 @@ pub struct Post { } impl Post { - pub async fn create( - user_id: &i64, - post: &String, - database_connection: &Pool, - ) -> Result { - post::create(user_id, post, database_connection).await + pub async fn create(user_id: &i64, post: &String) -> Result { + post::create(user_id, post).await } - pub async fn read( - creation_time: &DateTime, - database_connection: &Pool, - ) -> Result { - post::read(creation_time, database_connection).await + pub async fn read(creation_time: &DateTime) -> Result { + post::read(creation_time).await } pub async fn update( creation_time: &DateTime, user_id: &i64, post: &String, - database_connection: &Pool, ) -> Result { - post::update(creation_time, user_id, post, database_connection).await + post::update(creation_time, user_id, post).await } - pub async fn delete( - creation_time: &DateTime, - database_connection: &Pool, - ) -> Result { - post::delete(creation_time, database_connection).await + pub async fn delete(creation_time: &DateTime) -> Result { + post::delete(creation_time).await } - pub async fn read_all(database_connection: &Pool) -> Result, sqlx::Error> { - post::read_all(database_connection).await + pub async fn read_all() -> Result, sqlx::Error> { + post::read_all().await } - pub async fn read_all_for_user( - user_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - post::read_all_for_user(user_id, database_connection).await + pub async fn read_all_for_user(user_id: &i64) -> Result, sqlx::Error> { + post::read_all_for_user(user_id).await } } diff --git a/src/feature/post_interaction.rs b/src/feature/post_interaction.rs index 82e63b7..a4864f3 100644 --- a/src/feature/post_interaction.rs +++ b/src/feature/post_interaction.rs @@ -1,6 +1,5 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::post_interaction; @@ -17,43 +16,28 @@ impl PostInteraction { post_creation_time: &DateTime, user_id: &i64, interaction_id: &i64, - database_connection: &Pool, ) -> Result { - post_interaction::create( - post_creation_time, - user_id, - interaction_id, - database_connection, - ) - .await + post_interaction::create(post_creation_time, user_id, interaction_id).await } - pub async fn read( - interaction_time: &DateTime, - database_connection: &Pool, - ) -> Result { - post_interaction::read(interaction_time, database_connection).await + pub async fn read(interaction_time: &DateTime) -> Result { + post_interaction::read(interaction_time).await } pub async fn update( interaction_time: &DateTime, interaction_id: &i64, - database_connection: &Pool, ) -> Result { - post_interaction::update(interaction_time, interaction_id, database_connection).await + post_interaction::update(interaction_time, interaction_id).await } - pub async fn delete( - interaction_time: &DateTime, - database_connection: &Pool, - ) -> Result { - post_interaction::delete(interaction_time, database_connection).await + pub async fn delete(interaction_time: &DateTime) -> Result { + post_interaction::delete(interaction_time).await } pub async fn read_all_for_post( post_creation_time: &DateTime, - database_connection: &Pool, ) -> Result, sqlx::Error> { - post_interaction::read_all_for_post(post_creation_time, database_connection).await + post_interaction::read_all_for_post(post_creation_time).await } } diff --git a/src/feature/role.rs b/src/feature/role.rs index 3736572..83ce071 100644 --- a/src/feature/role.rs +++ b/src/feature/role.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::role; @@ -10,33 +9,23 @@ pub struct Role { } impl Role { - pub async fn create( - name: &String, - database_connection: &Pool, - ) -> Result { - role::create(name, database_connection).await + pub async fn create(name: &String) -> Result { + role::create(name).await } - pub async fn read(id: &i64, database_connection: &Pool) -> Result { - role::read(id, database_connection).await + pub async fn read(id: &i64) -> Result { + role::read(id).await } - pub async fn update( - id: &i64, - name: &String, - database_connection: &Pool, - ) -> Result { - role::update(id, name, database_connection).await + pub async fn update(id: &i64, name: &String) -> Result { + role::update(id, name).await } - pub async fn delete( - id: &i64, - database_connection: &Pool, - ) -> Result { - role::delete(id, database_connection).await + pub async fn delete(id: &i64) -> Result { + role::delete(id).await } - pub async fn read_all(database_connection: &Pool) -> Result, sqlx::Error> { - role::read_all(database_connection).await + pub async fn read_all() -> Result, sqlx::Error> { + role::read_all().await } } diff --git a/src/feature/user.rs b/src/feature/user.rs index b68e145..0d2fe40 100644 --- a/src/feature/user.rs +++ b/src/feature/user.rs @@ -1,6 +1,5 @@ use chrono::{DateTime, NaiveDate, Utc}; use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::user; @@ -28,16 +27,12 @@ impl User { surname: &String, gender: &bool, birth_date: &NaiveDate, - database_connection: &Pool, ) -> Result { - user::create(name, surname, gender, birth_date, database_connection).await + user::create(name, surname, gender, birth_date).await } - pub async fn read( - user_id: &i64, - database_connection: &Pool, - ) -> Result { - user::read(user_id, database_connection).await + pub async fn read(user_id: &i64) -> Result { + user::read(user_id).await } pub async fn update( @@ -47,144 +42,86 @@ impl User { gender: &bool, birth_date: &NaiveDate, role_id: &i64, - database_connection: &Pool, ) -> Result { - user::update( - user_id, - name, - surname, - gender, - birth_date, - role_id, - database_connection, - ) - .await + user::update(user_id, name, surname, gender, birth_date, role_id).await } - pub async fn delete( - user_id: &i64, - database_connection: &Pool, - ) -> Result { - user::delete(user_id, database_connection).await + pub async fn delete(user_id: &i64) -> Result { + user::delete(user_id).await } - pub async fn read_all(database_connection: &Pool) -> Result, sqlx::Error> { - user::read_all(database_connection).await + pub async fn read_all() -> Result, sqlx::Error> { + user::read_all().await } - pub async fn read_all_for_name( - name: &String, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_for_name(name, database_connection).await + pub async fn read_all_for_name(name: &String) -> Result, sqlx::Error> { + user::read_all_for_name(name).await } - pub async fn read_all_for_surname( - surname: &String, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_for_surname(surname, database_connection).await + pub async fn read_all_for_surname(surname: &String) -> Result, sqlx::Error> { + user::read_all_for_surname(surname).await } - pub async fn read_all_for_birth_date( - birth_date: &NaiveDate, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_for_birth_date(birth_date, database_connection).await + pub async fn read_all_for_birth_date(birth_date: &NaiveDate) -> Result, sqlx::Error> { + user::read_all_for_birth_date(birth_date).await } - pub async fn read_all_for_role( - role_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_for_role(role_id, database_connection).await + pub async fn read_all_for_role(role_id: &i64) -> Result, sqlx::Error> { + user::read_all_for_role(role_id).await } - pub async fn read_all_for_gender( - gender: &bool, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_for_gender(gender, database_connection).await + pub async fn read_all_for_gender(gender: &bool) -> Result, sqlx::Error> { + user::read_all_for_gender(gender).await } - pub async fn read_all_id( - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_id(database_connection).await + pub async fn read_all_id() -> Result, sqlx::Error> { + user::read_all_id().await } - pub async fn read_all_id_for_name( - name: &String, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_id_for_name(name, database_connection).await + pub async fn read_all_id_for_name(name: &String) -> Result, sqlx::Error> { + user::read_all_id_for_name(name).await } - pub async fn read_all_id_for_surname( - surname: &String, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_id_for_surname(surname, database_connection).await + pub async fn read_all_id_for_surname(surname: &String) -> Result, sqlx::Error> { + user::read_all_id_for_surname(surname).await } pub async fn read_all_id_for_birth_date( birth_date: &NaiveDate, - database_connection: &Pool, ) -> Result, sqlx::Error> { - user::read_all_id_for_birth_date(birth_date, database_connection).await + user::read_all_id_for_birth_date(birth_date).await } - pub async fn read_all_id_for_role( - role_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_id_for_role(role_id, database_connection).await + pub async fn read_all_id_for_role(role_id: &i64) -> Result, sqlx::Error> { + user::read_all_id_for_role(role_id).await } - pub async fn read_all_id_for_gender( - gender: &bool, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user::read_all_id_for_gender(gender, database_connection).await + pub async fn read_all_id_for_gender(gender: &bool) -> Result, sqlx::Error> { + user::read_all_id_for_gender(gender).await } - pub async fn count_all(database_connection: &Pool) -> Result { - user::count_all(database_connection).await + pub async fn count_all() -> Result { + user::count_all().await } - pub async fn count_all_for_name( - name: &String, - database_connection: &Pool, - ) -> Result { - user::count_all_for_name(name, database_connection).await + pub async fn count_all_for_name(name: &String) -> Result { + user::count_all_for_name(name).await } - pub async fn count_all_for_surname( - surname: &String, - database_connection: &Pool, - ) -> Result { - user::count_all_for_surname(surname, database_connection).await + pub async fn count_all_for_surname(surname: &String) -> Result { + user::count_all_for_surname(surname).await } - pub async fn count_all_for_birth_date( - birth_date: &NaiveDate, - database_connection: &Pool, - ) -> Result { - user::count_all_for_birth_date(birth_date, database_connection).await + pub async fn count_all_for_birth_date(birth_date: &NaiveDate) -> Result { + user::count_all_for_birth_date(birth_date).await } - pub async fn count_all_for_role( - role_id: &i64, - database_connection: &Pool, - ) -> Result { - user::count_all_for_role(role_id, database_connection).await + pub async fn count_all_for_role(role_id: &i64) -> Result { + user::count_all_for_role(role_id).await } - pub async fn count_all_for_gender( - gender: &bool, - database_connection: &Pool, - ) -> Result { - user::count_all_for_gender(gender, database_connection).await + pub async fn count_all_for_gender(gender: &bool) -> Result { + user::count_all_for_gender(gender).await } pub async fn is_builder(user: &User) -> bool { diff --git a/src/feature/user_contact.rs b/src/feature/user_contact.rs index 0ea8bc3..13dcdc2 100644 --- a/src/feature/user_contact.rs +++ b/src/feature/user_contact.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use sqlx::{Pool, Postgres}; use crate::database::user_contact; @@ -10,49 +9,27 @@ pub struct UserContact { } impl UserContact { - pub async fn create( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, - ) -> Result { - user_contact::create(user_id, contact_id, database_connection).await + pub async fn create(user_id: &i64, contact_id: &i64) -> Result { + user_contact::create(user_id, contact_id).await } - pub async fn read( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, - ) -> Result { - user_contact::read(user_id, contact_id, database_connection).await + pub async fn read(user_id: &i64, contact_id: &i64) -> Result { + user_contact::read(user_id, contact_id).await } - pub async fn update( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, - ) -> Result { - user_contact::update(user_id, contact_id, database_connection).await + pub async fn update(user_id: &i64, contact_id: &i64) -> Result { + user_contact::update(user_id, contact_id).await } - pub async fn delete( - user_id: &i64, - contact_id: &i64, - database_connection: &Pool, - ) -> Result { - user_contact::delete(user_id, contact_id, database_connection).await + pub async fn delete(user_id: &i64, contact_id: &i64) -> Result { + user_contact::delete(user_id, contact_id).await } - pub async fn read_all_for_user( - user_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user_contact::read_all_for_user(user_id, database_connection).await + pub async fn read_all_for_user(user_id: &i64) -> Result, sqlx::Error> { + user_contact::read_all_for_user(user_id).await } - pub async fn delete_all_for_user( - user_id: &i64, - database_connection: &Pool, - ) -> Result, sqlx::Error> { - user_contact::delete_all_for_user(user_id, database_connection).await + pub async fn delete_all_for_user(user_id: &i64) -> Result, sqlx::Error> { + user_contact::delete_all_for_user(user_id).await } } diff --git a/src/lib.rs b/src/lib.rs index 1148404..296bdd0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,14 +8,10 @@ pub mod utils; use std::sync::LazyLock; -use feature::auth::OneTimePassword; use sqlx::{Pool, Postgres}; -use tokio::sync::RwLock; use utils::naive_toml_parser; pub static SERVER_CONFIG: LazyLock = LazyLock::new(ServerConfig::default); -pub static ONE_TIME_PASSWORDS: LazyLock>> = - LazyLock::new(OneTimePassword::init); const DATABASE_CONFIG_FILE_LOCATION: &str = "./configs/database_config.toml"; const SERVER_CONFIG_FILE_LOCATION: &str = "./configs/server_config.toml"; diff --git a/src/main.rs b/src/main.rs index 306bf84..d093ffb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,17 +1,8 @@ -use rust_forum::{ - database::{establish_connection, set_database_up}, - server::start_server, - AppState, -}; +use rust_forum::server::start_server; #[tokio::main] async fn main() { println!("Hello, world!"); - let app_state = AppState { - database_connection: establish_connection().await, - }; - set_database_up(&app_state.database_connection).await; - - start_server(app_state).await; + start_server().await; } diff --git a/src/routing.rs b/src/routing.rs index 910306b..c0fb739 100644 --- a/src/routing.rs +++ b/src/routing.rs @@ -10,62 +10,30 @@ pub mod role; pub mod user; pub mod user_contact; -use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Router}; +use axum::{http::StatusCode, response::IntoResponse, routing::get, Router}; use tower::limit::ConcurrencyLimitLayer; use tower_http::cors::CorsLayer; -use crate::{database, AppState}; +use crate::database; -pub async fn route(concurrency_limit: &usize, State(app_state): State) -> Router { +pub async fn route(concurrency_limit: &usize) -> Router { Router::new() .route("/", get(alive)) - .route_layer(axum::middleware::from_fn_with_state( - app_state.clone(), - middleware::pass, - )) - .nest( - "/roles", - role::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/users", - user::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/posts", - post::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/comments", - comment::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/interactions", - interaction::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/post_interactions", - post_interaction::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/comment_interactions", - comment_interaction::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/contacts", - contact::route(axum::extract::State(app_state.clone())), - ) - .nest( - "/user_contacts", - user_contact::route(axum::extract::State(app_state.clone())), - ) + .nest("/roles", role::route()) + .nest("/users", user::route()) + .nest("/posts", post::route()) + .nest("/comments", comment::route()) + .nest("/interactions", interaction::route()) + .nest("/post_interactions", post_interaction::route()) + .nest("/comment_interactions", comment_interaction::route()) + .nest("/contacts", contact::route()) + .nest("/user_contacts", user_contact::route()) .layer(CorsLayer::permissive()) .layer(ConcurrencyLimitLayer::new(*concurrency_limit)) - .with_state(app_state) } -pub async fn alive(State(app_state): State) -> impl IntoResponse { - match database::is_alive(&app_state.database_connection).await { +pub async fn alive() -> impl IntoResponse { + match database::is_alive().await { true => StatusCode::OK, false => StatusCode::SERVICE_UNAVAILABLE, } diff --git a/src/routing/comment.rs b/src/routing/comment.rs index 2d7826c..5bbb1b9 100644 --- a/src/routing/comment.rs +++ b/src/routing/comment.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -8,7 +8,7 @@ use axum::{ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use crate::{feature::comment::Comment, AppState}; +use crate::feature::comment::Comment; #[derive(Debug, Serialize, Deserialize)] struct CreateComment { @@ -23,25 +23,20 @@ struct UpdateComment { comment: String, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:creation_time", get(read)) .route("/", patch(update)) .route("/:creation_time", delete(delete_)) .route("/posts/:post_creation_time", get(read_all_for_post)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_comment): Json, -) -> impl IntoResponse { +async fn create(Json(create_comment): Json) -> impl IntoResponse { match Comment::create( &create_comment.post_creation_time, &create_comment.user_id, &create_comment.comment, - &app_state.database_connection, ) .await { @@ -53,11 +48,8 @@ async fn create( } } -async fn read( - State(app_state): State, - Path(creation_time): Path>, -) -> impl IntoResponse { - match Comment::read(&creation_time, &app_state.database_connection).await { +async fn read(Path(creation_time): Path>) -> impl IntoResponse { + match Comment::read(&creation_time).await { Ok(comment) => (StatusCode::OK, Json(serde_json::json!(comment))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -66,17 +58,8 @@ async fn read( } } -async fn update( - State(app_state): State, - Json(update_comment): Json, -) -> impl IntoResponse { - match Comment::update( - &update_comment.creation_time, - &update_comment.comment, - &app_state.database_connection, - ) - .await - { +async fn update(Json(update_comment): Json) -> impl IntoResponse { + match Comment::update(&update_comment.creation_time, &update_comment.comment).await { Ok(comment) => (StatusCode::ACCEPTED, Json(serde_json::json!(comment))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -85,11 +68,8 @@ async fn update( } } -async fn delete_( - State(app_state): State, - Path(creation_time): Path>, -) -> impl IntoResponse { - match Comment::delete(&creation_time, &app_state.database_connection).await { +async fn delete_(Path(creation_time): Path>) -> impl IntoResponse { + match Comment::delete(&creation_time).await { Ok(comment) => (StatusCode::NO_CONTENT, Json(serde_json::json!(comment))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -98,11 +78,8 @@ async fn delete_( } } -async fn read_all_for_post( - State(app_state): State, - Path(post_creation_time): Path>, -) -> impl IntoResponse { - match Comment::read_all_for_post(&post_creation_time, &app_state.database_connection).await { +async fn read_all_for_post(Path(post_creation_time): Path>) -> impl IntoResponse { + match Comment::read_all_for_post(&post_creation_time).await { Ok(comments) => (StatusCode::OK, Json(serde_json::json!(comments))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/comment_interaction.rs b/src/routing/comment_interaction.rs index c6ada14..b17eaf8 100644 --- a/src/routing/comment_interaction.rs +++ b/src/routing/comment_interaction.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -8,7 +8,7 @@ use axum::{ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use crate::{feature::comment_interaction::CommentInteraction, AppState}; +use crate::feature::comment_interaction::CommentInteraction; #[derive(Debug, Serialize, Deserialize)] struct CreateCommentInteraction { @@ -25,7 +25,7 @@ struct UpdateCommentInteraction { pub user_id: i64, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:interaction_time", get(read)) @@ -35,18 +35,15 @@ pub fn route(State(app_state): State) -> Router { "/comments/:comment_creation_time", get(read_all_for_comment), ) - .with_state(app_state) } async fn create( - State(app_state): State, Json(create_comment_interaction): Json, ) -> impl IntoResponse { match CommentInteraction::create( &create_comment_interaction.comment_creation_time, &create_comment_interaction.user_id, &create_comment_interaction.interaction_id, - &app_state.database_connection, ) .await { @@ -61,11 +58,8 @@ async fn create( } } -async fn read( - State(app_state): State, - Path(interaction_time): Path>, -) -> impl IntoResponse { - match CommentInteraction::read(&interaction_time, &app_state.database_connection).await { +async fn read(Path(interaction_time): Path>) -> impl IntoResponse { + match CommentInteraction::read(&interaction_time).await { Ok(comment_interaction) => (StatusCode::OK, Json(serde_json::json!(comment_interaction))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -75,13 +69,11 @@ async fn read( } async fn update( - State(app_state): State, Json(update_comment_interaction): Json, ) -> impl IntoResponse { match CommentInteraction::update( &update_comment_interaction.interaction_time, &update_comment_interaction.interaction_id, - &app_state.database_connection, ) .await { @@ -96,11 +88,8 @@ async fn update( } } -async fn delete_( - State(app_state): State, - Path(interaction_time): Path>, -) -> impl IntoResponse { - match CommentInteraction::delete(&interaction_time, &app_state.database_connection).await { +async fn delete_(Path(interaction_time): Path>) -> impl IntoResponse { + match CommentInteraction::delete(&interaction_time).await { Ok(comment_interaction) => ( StatusCode::NO_CONTENT, Json(serde_json::json!(comment_interaction)), @@ -113,15 +102,9 @@ async fn delete_( } async fn read_all_for_comment( - State(app_state): State, Path(comment_creation_time): Path>, ) -> impl IntoResponse { - match CommentInteraction::read_all_for_comment( - &comment_creation_time, - &app_state.database_connection, - ) - .await - { + match CommentInteraction::read_all_for_comment(&comment_creation_time).await { Ok(comment_interactions) => ( StatusCode::OK, Json(serde_json::json!(comment_interactions)), diff --git a/src/routing/contact.rs b/src/routing/contact.rs index d404ad5..d4d1f27 100644 --- a/src/routing/contact.rs +++ b/src/routing/contact.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -7,7 +7,7 @@ use axum::{ }; use serde::{Deserialize, Serialize}; -use crate::{feature::contact::Contact, AppState}; +use crate::feature::contact::Contact; #[derive(Debug, Serialize, Deserialize)] struct CreateContact { @@ -20,21 +20,17 @@ struct UpdateContact { name: String, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:id", get(read)) .route("/", patch(update)) .route("/:id", delete(delete_)) .route("/", get(read_all)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_contact): Json, -) -> impl IntoResponse { - match Contact::create(&create_contact.name, &app_state.database_connection).await { +async fn create(Json(create_contact): Json) -> impl IntoResponse { + match Contact::create(&create_contact.name).await { Ok(contact) => (StatusCode::CREATED, Json(serde_json::json!(contact))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -43,8 +39,8 @@ async fn create( } } -async fn read(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match Contact::read(&id, &app_state.database_connection).await { +async fn read(Path(id): Path) -> impl IntoResponse { + match Contact::read(&id).await { Ok(contact) => (StatusCode::OK, Json(serde_json::json!(contact))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -53,17 +49,8 @@ async fn read(State(app_state): State, Path(id): Path) -> impl In } } -async fn update( - State(app_state): State, - Json(update_contact): Json, -) -> impl IntoResponse { - match Contact::update( - &update_contact.id, - &update_contact.name, - &app_state.database_connection, - ) - .await - { +async fn update(Json(update_contact): Json) -> impl IntoResponse { + match Contact::update(&update_contact.id, &update_contact.name).await { Ok(contact) => (StatusCode::ACCEPTED, Json(serde_json::json!(contact))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -72,8 +59,8 @@ async fn update( } } -async fn delete_(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match Contact::delete(&id, &app_state.database_connection).await { +async fn delete_(Path(id): Path) -> impl IntoResponse { + match Contact::delete(&id).await { Ok(contact) => (StatusCode::NO_CONTENT, Json(serde_json::json!(contact))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -82,8 +69,8 @@ async fn delete_(State(app_state): State, Path(id): Path) -> impl } } -async fn read_all(State(app_state): State) -> impl IntoResponse { - match Contact::read_all(&app_state.database_connection).await { +async fn read_all() -> impl IntoResponse { + match Contact::read_all().await { Ok(contacts) => (StatusCode::OK, Json(serde_json::json!(contacts))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/interaction.rs b/src/routing/interaction.rs index fb16ae6..e098688 100644 --- a/src/routing/interaction.rs +++ b/src/routing/interaction.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -7,7 +7,7 @@ use axum::{ }; use serde::{Deserialize, Serialize}; -use crate::{feature::interaction::Interaction, AppState}; +use crate::feature::interaction::Interaction; #[derive(Debug, Serialize, Deserialize)] struct CreateInteraction { @@ -20,21 +20,17 @@ struct UpdateInteraction { name: String, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:id", get(read)) .route("/", patch(update)) .route("/:id", delete(delete_)) .route("/", get(read_all)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_interaction): Json, -) -> impl IntoResponse { - match Interaction::create(&create_interaction.name, &app_state.database_connection).await { +async fn create(Json(create_interaction): Json) -> impl IntoResponse { + match Interaction::create(&create_interaction.name).await { Ok(interaction) => (StatusCode::CREATED, Json(serde_json::json!(interaction))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -43,8 +39,8 @@ async fn create( } } -async fn read(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match Interaction::read(&id, &app_state.database_connection).await { +async fn read(Path(id): Path) -> impl IntoResponse { + match Interaction::read(&id).await { Ok(interaction) => (StatusCode::OK, Json(serde_json::json!(interaction))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -53,17 +49,8 @@ async fn read(State(app_state): State, Path(id): Path) -> impl In } } -async fn update( - State(app_state): State, - Json(update_interaction): Json, -) -> impl IntoResponse { - match Interaction::update( - &update_interaction.id, - &update_interaction.name, - &app_state.database_connection, - ) - .await - { +async fn update(Json(update_interaction): Json) -> impl IntoResponse { + match Interaction::update(&update_interaction.id, &update_interaction.name).await { Ok(interaction) => (StatusCode::ACCEPTED, Json(serde_json::json!(interaction))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -72,8 +59,8 @@ async fn update( } } -async fn delete_(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match Interaction::delete(&id, &app_state.database_connection).await { +async fn delete_(Path(id): Path) -> impl IntoResponse { + match Interaction::delete(&id).await { Ok(interaction) => (StatusCode::NO_CONTENT, Json(serde_json::json!(interaction))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -82,8 +69,8 @@ async fn delete_(State(app_state): State, Path(id): Path) -> impl } } -async fn read_all(State(app_state): State) -> impl IntoResponse { - match Interaction::read_all(&app_state.database_connection).await { +async fn read_all() -> impl IntoResponse { + match Interaction::read_all().await { Ok(interactions) => (StatusCode::OK, Json(serde_json::json!(interactions))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/login.rs b/src/routing/login.rs index 1e118f8..c6d8aa3 100644 --- a/src/routing/login.rs +++ b/src/routing/login.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -7,10 +7,7 @@ use axum::{ }; use serde::{Deserialize, Serialize}; -use crate::{ - feature::{auth::OneTimePassword, login::Login}, - AppState, -}; +use crate::feature::{auth::OneTimePassword, login::Login}; #[derive(Debug, Serialize, Deserialize)] struct CreateLogin { @@ -23,7 +20,7 @@ struct UpdateLogin { pub token: String, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/users/:user_id/token/:token", get(read)) @@ -32,28 +29,17 @@ pub fn route(State(app_state): State) -> Router { .route("/users/:user_id", get(read_all_for_user)) .route("/users/:user_id", delete(delete_all_for_user)) .route("/count/users/:user_id", get(count_all_for_user)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_login): Json, -) -> impl IntoResponse { +async fn create(Json(create_login): Json) -> impl IntoResponse { match OneTimePassword::verify(&create_login.one_time_password).await { - true => { - match Login::create( - &create_login.one_time_password.user_id, - &app_state.database_connection, - ) - .await - { - Ok(login) => (StatusCode::CREATED, Json(serde_json::json!(login))), - Err(err_val) => ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!(err_val.to_string())), - ), - } - } + true => match Login::create(&create_login.one_time_password.user_id).await { + Ok(login) => (StatusCode::CREATED, Json(serde_json::json!(login))), + Err(err_val) => ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!(err_val.to_string())), + ), + }, false => ( StatusCode::BAD_REQUEST, Json(serde_json::json!( @@ -63,11 +49,8 @@ async fn create( } } -async fn read( - State(app_state): State, - Path((user_id, token)): Path<(i64, String)>, -) -> impl IntoResponse { - match Login::read(&user_id, &token, &app_state.database_connection).await { +async fn read(Path((user_id, token)): Path<(i64, String)>) -> impl IntoResponse { + match Login::read(&user_id, &token).await { Ok(login) => (StatusCode::OK, Json(serde_json::json!(login))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -76,17 +59,8 @@ async fn read( } } -async fn update( - State(app_state): State, - Json(update_role): Json, -) -> impl IntoResponse { - match Login::update( - &update_role.user_id, - &update_role.token, - &app_state.database_connection, - ) - .await - { +async fn update(Json(update_role): Json) -> impl IntoResponse { + match Login::update(&update_role.user_id, &update_role.token).await { Ok(login) => (StatusCode::ACCEPTED, Json(serde_json::json!(login))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -95,11 +69,8 @@ async fn update( } } -async fn delete_( - State(app_state): State, - Path((user_id, token)): Path<(i64, String)>, -) -> impl IntoResponse { - match Login::delete(&user_id, &token, &app_state.database_connection).await { +async fn delete_(Path((user_id, token)): Path<(i64, String)>) -> impl IntoResponse { + match Login::delete(&user_id, &token).await { Ok(login) => (StatusCode::NO_CONTENT, Json(serde_json::json!(login))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -108,11 +79,8 @@ async fn delete_( } } -async fn read_all_for_user( - State(app_state): State, - Path(user_id): Path, -) -> impl IntoResponse { - match Login::read_all_for_user(&user_id, &app_state.database_connection).await { +async fn read_all_for_user(Path(user_id): Path) -> impl IntoResponse { + match Login::read_all_for_user(&user_id).await { Ok(logins) => (StatusCode::OK, Json(serde_json::json!(logins))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -121,11 +89,8 @@ async fn read_all_for_user( } } -async fn delete_all_for_user( - State(app_state): State, - Path(user_id): Path, -) -> impl IntoResponse { - match Login::delete_all_for_user(&user_id, &app_state.database_connection).await { +async fn delete_all_for_user(Path(user_id): Path) -> impl IntoResponse { + match Login::delete_all_for_user(&user_id).await { Ok(logins) => (StatusCode::OK, Json(serde_json::json!(logins))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -134,11 +99,8 @@ async fn delete_all_for_user( } } -async fn count_all_for_user( - State(app_state): State, - Path(user_id): Path, -) -> impl IntoResponse { - match Login::count_all_for_user(&user_id, &app_state.database_connection).await { +async fn count_all_for_user(Path(user_id): Path) -> impl IntoResponse { + match Login::count_all_for_user(&user_id).await { Ok(login_count) => (StatusCode::OK, Json(serde_json::json!(login_count))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/middleware.rs b/src/routing/middleware.rs index 6e6cf5c..3bf9546 100644 --- a/src/routing/middleware.rs +++ b/src/routing/middleware.rs @@ -2,17 +2,13 @@ use std::sync::Arc; use axum::{ body::{to_bytes, Body}, - extract::{Request, State}, - http::{self, StatusCode}, + extract::Request, + http::{self, Method, StatusCode}, middleware::Next, response::IntoResponse, }; -use sqlx::{Pool, Postgres}; -use crate::{ - feature::{login::TokenMeta, user::User}, - AppState, -}; +use crate::feature::{login::TokenMeta, user::User}; #[derive(Debug)] struct UserAndRequest { @@ -20,6 +16,12 @@ struct UserAndRequest { request: Request, } +#[derive(Debug)] +struct TargetUserAndRequest { + target_user: User, + request: Request, +} + #[derive(Debug)] struct UserAndTargetUserAndRequest { user: User, @@ -27,10 +29,7 @@ struct UserAndTargetUserAndRequest { request: Request, } -async fn user_extraction( - request: Request, - database_connection: &Pool, -) -> Option { +async fn user_extraction(request: Request) -> Option { if let Some(authorization_header) = request.headers().get(http::header::AUTHORIZATION) { if let Ok(authorization_header) = authorization_header.to_str() { if let Some((bearer, authorization_header)) = authorization_header.split_once(' ') { @@ -39,7 +38,7 @@ async fn user_extraction( TokenMeta::verify_token(&authorization_header.to_string()).await { return Some(UserAndRequest { - user: User::read(&claims.custom, database_connection).await.ok()?, + user: User::read(&claims.custom).await.ok()?, request, }); } @@ -50,29 +49,26 @@ async fn user_extraction( None } -async fn target_user_extraction_from_json( - json: &serde_json::Value, - database_connection: &Pool, -) -> Option { - if let Some(target_user_id) = json.get("user_id") { - if target_user_id.is_i64() { - if let Some(target_user_id) = target_user_id.as_i64() { - return User::read(&target_user_id, database_connection).await.ok(); +async fn target_user_extraction_from_uri(request: Request) -> Option { + let uri_parts = request.uri().path().split('/').collect::>(); + for (index, uri_part) in uri_parts.iter().enumerate() { + if *uri_part == "users" { + if let Some(target_user_id) = uri_parts.get(index) { + if let Ok(target_user_id) = (*target_user_id).parse::() { + if let Ok(target_user) = User::read(&target_user_id).await { + return Some(TargetUserAndRequest { + target_user, + request, + }); + } + } } } } - None } -async fn user_and_target_user_extraction( - request: Request, - database_connection: &Pool, -) -> Option { - let user_and_request = user_extraction(request, database_connection).await?; - let user = user_and_request.user; - let request = user_and_request.request; - +async fn target_user_extraction_from_json(request: Request) -> Option { let (parts, body) = request.into_parts(); let bytes = to_bytes(body, usize::MAX).await.ok()?; let json: serde_json::Value = serde_json::from_slice(&bytes).ok()?; @@ -80,19 +76,45 @@ async fn user_and_target_user_extraction( let body = Body::from(json.to_string()); let request = Request::from_parts(parts, body); + if let Some(target_user_id) = json.get("user_id") { + if target_user_id.is_i64() { + if let Some(target_user_id) = target_user_id.as_i64() { + if let Ok(target_user) = User::read(&target_user_id).await { + return Some(TargetUserAndRequest { + target_user, + request, + }); + } + } + } + } + + None +} + +async fn user_and_target_user_extraction(request: Request) -> Option { + let user_and_request = user_extraction(request).await?; + let user = user_and_request.user; + let request = user_and_request.request; + + let target_user_and_request = if request.method() == Method::GET { + target_user_extraction_from_uri(request).await + } else { + target_user_extraction_from_json(request).await + }?; + + let target_user = target_user_and_request.target_user; + let request = target_user_and_request.request; + Some(UserAndTargetUserAndRequest { user, - target_user: target_user_extraction_from_json(&json, database_connection).await?, + target_user, request, }) } -pub async fn pass( - State(app_state): State, - request: Request, - next: Next, -) -> Result { - match user_extraction(request, &app_state.database_connection).await { +pub async fn pass(request: Request, next: Next) -> Result { + match user_extraction(request).await { Some(user_and_request) => { let user = Arc::new(user_and_request.user); let mut request = user_and_request.request; @@ -105,12 +127,8 @@ pub async fn pass( } } -pub async fn pass_builder( - State(app_state): State, - request: Request, - next: Next, -) -> Result { - if let Some(user_and_request) = user_extraction(request, &app_state.database_connection).await { +pub async fn pass_builder(request: Request, next: Next) -> Result { + if let Some(user_and_request) = user_extraction(request).await { let user = user_and_request.user; let mut request = user_and_request.request; @@ -124,31 +142,11 @@ pub async fn pass_builder( Err(StatusCode::FORBIDDEN) } -pub async fn pass_admin( - State(app_state): State, - request: Request, - next: Next, -) -> Result { - if let Some(user_and_request) = user_extraction(request, &app_state.database_connection).await { - let user = user_and_request.user; - let mut request = user_and_request.request; - - if User::is_admin(&user).await { - let user = Arc::new(user); - request.extensions_mut().insert(user); - - return Ok(next.run(request).await); - } - } - Err(StatusCode::FORBIDDEN) -} - pub async fn pass_builder_or_admin( - State(app_state): State, request: Request, next: Next, ) -> Result { - if let Some(user_and_request) = user_extraction(request, &app_state.database_connection).await { + if let Some(user_and_request) = user_extraction(request).await { let user = user_and_request.user; let mut request = user_and_request.request; @@ -162,14 +160,8 @@ pub async fn pass_builder_or_admin( Err(StatusCode::FORBIDDEN) } -pub async fn pass_self( - State(app_state): State, - request: Request, - next: Next, -) -> Result { - if let Some(user_and_target_user_and_request) = - user_and_target_user_extraction(request, &app_state.database_connection).await - { +pub async fn pass_self(request: Request, next: Next) -> Result { + if let Some(user_and_target_user_and_request) = user_and_target_user_extraction(request).await { let user = user_and_target_user_and_request.user; let target_user = user_and_target_user_and_request.target_user; let mut request = user_and_target_user_and_request.request; @@ -184,14 +176,8 @@ pub async fn pass_self( Err(StatusCode::FORBIDDEN) } -pub async fn pass_higher( - State(app_state): State, - request: Request, - next: Next, -) -> Result { - if let Some(user_and_target_user_and_request) = - user_and_target_user_extraction(request, &app_state.database_connection).await - { +pub async fn pass_higher(request: Request, next: Next) -> Result { + if let Some(user_and_target_user_and_request) = user_and_target_user_extraction(request).await { let user = user_and_target_user_and_request.user; let target_user = user_and_target_user_and_request.target_user; let mut request = user_and_target_user_and_request.request; @@ -207,13 +193,10 @@ pub async fn pass_higher( } pub async fn pass_higher_or_self( - State(app_state): State, request: Request, next: Next, ) -> Result { - if let Some(user_and_target_user_and_request) = - user_and_target_user_extraction(request, &app_state.database_connection).await - { + if let Some(user_and_target_user_and_request) = user_and_target_user_extraction(request).await { let user = user_and_target_user_and_request.user; let target_user = user_and_target_user_and_request.target_user; let mut request = user_and_target_user_and_request.request; diff --git a/src/routing/post.rs b/src/routing/post.rs index 210496f..486df47 100644 --- a/src/routing/post.rs +++ b/src/routing/post.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -8,7 +8,7 @@ use axum::{ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use crate::{feature::post::Post, AppState}; +use crate::feature::post::Post; #[derive(Debug, Serialize, Deserialize)] struct CreatePost { @@ -23,27 +23,17 @@ struct UpdatePost { post: String, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:creation_time", get(read)) .route("/", patch(update)) .route("/:creation_time", delete(delete_)) .route("/", get(read_all)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_post): Json, -) -> impl IntoResponse { - match Post::create( - &create_post.user_id, - &create_post.post, - &app_state.database_connection, - ) - .await - { +async fn create(Json(create_post): Json) -> impl IntoResponse { + match Post::create(&create_post.user_id, &create_post.post).await { Ok(post) => (StatusCode::CREATED, Json(serde_json::json!(post))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -52,11 +42,8 @@ async fn create( } } -async fn read( - State(app_state): State, - Path(creation_time): Path>, -) -> impl IntoResponse { - match Post::read(&creation_time, &app_state.database_connection).await { +async fn read(Path(creation_time): Path>) -> impl IntoResponse { + match Post::read(&creation_time).await { Ok(post) => (StatusCode::OK, Json(serde_json::json!(post))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -65,15 +52,11 @@ async fn read( } } -async fn update( - State(app_state): State, - Json(update_role): Json, -) -> impl IntoResponse { +async fn update(Json(update_role): Json) -> impl IntoResponse { match Post::update( &update_role.creation_time, &update_role.user_id, &update_role.post, - &app_state.database_connection, ) .await { @@ -85,11 +68,8 @@ async fn update( } } -async fn delete_( - State(app_state): State, - Path(creation_time): Path>, -) -> impl IntoResponse { - match Post::delete(&creation_time, &app_state.database_connection).await { +async fn delete_(Path(creation_time): Path>) -> impl IntoResponse { + match Post::delete(&creation_time).await { Ok(post) => (StatusCode::NO_CONTENT, Json(serde_json::json!(post))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -98,8 +78,8 @@ async fn delete_( } } -async fn read_all(State(app_state): State) -> impl IntoResponse { - match Post::read_all(&app_state.database_connection).await { +async fn read_all() -> impl IntoResponse { + match Post::read_all().await { Ok(posts) => (StatusCode::OK, Json(serde_json::json!(posts))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/post_interaction.rs b/src/routing/post_interaction.rs index 9a932a0..5c7c581 100644 --- a/src/routing/post_interaction.rs +++ b/src/routing/post_interaction.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -8,7 +8,7 @@ use axum::{ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use crate::{feature::post_interaction::PostInteraction, AppState}; +use crate::feature::post_interaction::PostInteraction; #[derive(Debug, Serialize, Deserialize)] struct CreatePostInteraction { @@ -25,25 +25,20 @@ struct UpdatePostInteraction { pub user_id: i64, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:interaction_time", get(read)) .route("/", patch(update)) .route("/:interaction_time", delete(delete_)) .route("/posts/:post_creation_time", get(read_all_for_post)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_post_interaction): Json, -) -> impl IntoResponse { +async fn create(Json(create_post_interaction): Json) -> impl IntoResponse { match PostInteraction::create( &create_post_interaction.post_creation_time, &create_post_interaction.user_id, &create_post_interaction.interaction_id, - &app_state.database_connection, ) .await { @@ -58,11 +53,8 @@ async fn create( } } -async fn read( - State(app_state): State, - Path(interaction_time): Path>, -) -> impl IntoResponse { - match PostInteraction::read(&interaction_time, &app_state.database_connection).await { +async fn read(Path(interaction_time): Path>) -> impl IntoResponse { + match PostInteraction::read(&interaction_time).await { Ok(post_interaction) => (StatusCode::OK, Json(serde_json::json!(post_interaction))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -71,14 +63,10 @@ async fn read( } } -async fn update( - State(app_state): State, - Json(update_post_interaction): Json, -) -> impl IntoResponse { +async fn update(Json(update_post_interaction): Json) -> impl IntoResponse { match PostInteraction::update( &update_post_interaction.interaction_time, &update_post_interaction.interaction_id, - &app_state.database_connection, ) .await { @@ -93,11 +81,8 @@ async fn update( } } -async fn delete_( - State(app_state): State, - Path(interaction_time): Path>, -) -> impl IntoResponse { - match PostInteraction::delete(&interaction_time, &app_state.database_connection).await { +async fn delete_(Path(interaction_time): Path>) -> impl IntoResponse { + match PostInteraction::delete(&interaction_time).await { Ok(post_interaction) => ( StatusCode::NO_CONTENT, Json(serde_json::json!(post_interaction)), @@ -109,13 +94,8 @@ async fn delete_( } } -async fn read_all_for_post( - State(app_state): State, - Path(post_creation_time): Path>, -) -> impl IntoResponse { - match PostInteraction::read_all_for_post(&post_creation_time, &app_state.database_connection) - .await - { +async fn read_all_for_post(Path(post_creation_time): Path>) -> impl IntoResponse { + match PostInteraction::read_all_for_post(&post_creation_time).await { Ok(post_interactions) => (StatusCode::OK, Json(serde_json::json!(post_interactions))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/role.rs b/src/routing/role.rs index 57ebbac..840d158 100644 --- a/src/routing/role.rs +++ b/src/routing/role.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -7,7 +7,9 @@ use axum::{ }; use serde::{Deserialize, Serialize}; -use crate::{feature::role::Role, AppState}; +use crate::feature::role::Role; + +use super::middleware; #[derive(Debug, Serialize, Deserialize)] struct CreateRole { @@ -20,21 +22,22 @@ struct UpdateRole { name: String, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) + .route_layer(axum::middleware::from_fn(middleware::pass_builder_or_admin)) .route("/:id", get(read)) + .route_layer(axum::middleware::from_fn(middleware::pass)) .route("/", patch(update)) + .route_layer(axum::middleware::from_fn(middleware::pass_builder_or_admin)) .route("/:id", delete(delete_)) + .route_layer(axum::middleware::from_fn(middleware::pass_builder_or_admin)) .route("/", get(read_all)) - .with_state(app_state) + .route_layer(axum::middleware::from_fn(middleware::pass)) } -async fn create( - State(app_state): State, - Json(create_role): Json, -) -> impl IntoResponse { - match Role::create(&create_role.name, &app_state.database_connection).await { +async fn create(Json(create_role): Json) -> impl IntoResponse { + match Role::create(&create_role.name).await { Ok(role) => (StatusCode::CREATED, Json(serde_json::json!(role))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -43,8 +46,8 @@ async fn create( } } -async fn read(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match Role::read(&id, &app_state.database_connection).await { +async fn read(Path(id): Path) -> impl IntoResponse { + match Role::read(&id).await { Ok(role) => (StatusCode::OK, Json(serde_json::json!(role))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -53,17 +56,8 @@ async fn read(State(app_state): State, Path(id): Path) -> impl In } } -async fn update( - State(app_state): State, - Json(update_role): Json, -) -> impl IntoResponse { - match Role::update( - &update_role.id, - &update_role.name, - &app_state.database_connection, - ) - .await - { +async fn update(Json(update_role): Json) -> impl IntoResponse { + match Role::update(&update_role.id, &update_role.name).await { Ok(role) => (StatusCode::ACCEPTED, Json(serde_json::json!(role))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -72,8 +66,8 @@ async fn update( } } -async fn delete_(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match Role::delete(&id, &app_state.database_connection).await { +async fn delete_(Path(id): Path) -> impl IntoResponse { + match Role::delete(&id).await { Ok(role) => (StatusCode::NO_CONTENT, Json(serde_json::json!(role))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -82,8 +76,8 @@ async fn delete_(State(app_state): State, Path(id): Path) -> impl } } -async fn read_all(State(app_state): State) -> impl IntoResponse { - match Role::read_all(&app_state.database_connection).await { +async fn read_all() -> impl IntoResponse { + match Role::read_all().await { Ok(roles) => (StatusCode::OK, Json(serde_json::json!(roles))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/user.rs b/src/routing/user.rs index a0f1cde..765d25b 100644 --- a/src/routing/user.rs +++ b/src/routing/user.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -8,7 +8,7 @@ use axum::{ use chrono::NaiveDate; use serde::{Deserialize, Serialize}; -use crate::{feature::user::User, AppState}; +use crate::feature::user::User; #[derive(Debug, Serialize, Deserialize)] struct CreateUser { @@ -28,7 +28,7 @@ struct UpdateUser { role_id: i64, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/:id", get(read)) @@ -58,19 +58,14 @@ pub fn route(State(app_state): State) -> Router { ) .route("/count/roles/:role", get(count_all_for_role)) .route("/count/genders/:gender", get(count_all_for_gender)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_user): Json, -) -> impl IntoResponse { +async fn create(Json(create_user): Json) -> impl IntoResponse { match User::create( &create_user.name, &create_user.surname, &create_user.gender, &create_user.birth_date, - &app_state.database_connection, ) .await { @@ -82,8 +77,8 @@ async fn create( } } -async fn read(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match User::read(&id, &app_state.database_connection).await { +async fn read(Path(id): Path) -> impl IntoResponse { + match User::read(&id).await { Ok(user) => (StatusCode::OK, Json(serde_json::json!(user))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -92,10 +87,7 @@ async fn read(State(app_state): State, Path(id): Path) -> impl In } } -async fn update( - State(app_state): State, - Json(update_user): Json, -) -> impl IntoResponse { +async fn update(Json(update_user): Json) -> impl IntoResponse { match User::update( &update_user.id, &update_user.name, @@ -103,7 +95,6 @@ async fn update( &update_user.gender, &update_user.birth_date, &update_user.role_id, - &app_state.database_connection, ) .await { @@ -115,8 +106,8 @@ async fn update( } } -async fn delete_(State(app_state): State, Path(id): Path) -> impl IntoResponse { - match User::delete(&id, &app_state.database_connection).await { +async fn delete_(Path(id): Path) -> impl IntoResponse { + match User::delete(&id).await { Ok(user) => (StatusCode::NO_CONTENT, Json(serde_json::json!(user))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -125,8 +116,8 @@ async fn delete_(State(app_state): State, Path(id): Path) -> impl } } -async fn read_all(State(app_state): State) -> impl IntoResponse { - match User::read_all(&app_state.database_connection).await { +async fn read_all() -> impl IntoResponse { + match User::read_all().await { Ok(users) => (StatusCode::OK, Json(serde_json::json!(users))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -135,11 +126,8 @@ async fn read_all(State(app_state): State) -> impl IntoResponse { } } -async fn read_all_for_name( - State(app_state): State, - Path(name): Path, -) -> impl IntoResponse { - match User::read_all_for_name(&name, &app_state.database_connection).await { +async fn read_all_for_name(Path(name): Path) -> impl IntoResponse { + match User::read_all_for_name(&name).await { Ok(users) => (StatusCode::OK, Json(serde_json::json!(users))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -148,11 +136,8 @@ async fn read_all_for_name( } } -async fn read_all_for_surname( - State(app_state): State, - Path(surname): Path, -) -> impl IntoResponse { - match User::read_all_for_surname(&surname, &app_state.database_connection).await { +async fn read_all_for_surname(Path(surname): Path) -> impl IntoResponse { + match User::read_all_for_surname(&surname).await { Ok(users) => (StatusCode::OK, Json(serde_json::json!(users))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -161,11 +146,8 @@ async fn read_all_for_surname( } } -async fn read_all_for_birth_date( - State(app_state): State, - Path(birth_date): Path, -) -> impl IntoResponse { - match User::read_all_for_birth_date(&birth_date, &app_state.database_connection).await { +async fn read_all_for_birth_date(Path(birth_date): Path) -> impl IntoResponse { + match User::read_all_for_birth_date(&birth_date).await { Ok(users) => (StatusCode::OK, Json(serde_json::json!(users))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -174,11 +156,8 @@ async fn read_all_for_birth_date( } } -async fn read_all_for_role( - State(app_state): State, - Path(role_id): Path, -) -> impl IntoResponse { - match User::read_all_for_role(&role_id, &app_state.database_connection).await { +async fn read_all_for_role(Path(role_id): Path) -> impl IntoResponse { + match User::read_all_for_role(&role_id).await { Ok(users) => (StatusCode::OK, Json(serde_json::json!(users))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -187,11 +166,8 @@ async fn read_all_for_role( } } -async fn read_all_for_gender( - State(app_state): State, - Path(gender): Path, -) -> impl IntoResponse { - match User::read_all_for_gender(&gender, &app_state.database_connection).await { +async fn read_all_for_gender(Path(gender): Path) -> impl IntoResponse { + match User::read_all_for_gender(&gender).await { Ok(users) => (StatusCode::OK, Json(serde_json::json!(users))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -200,8 +176,8 @@ async fn read_all_for_gender( } } -async fn read_all_id(State(app_state): State) -> impl IntoResponse { - match User::read_all_id(&app_state.database_connection).await { +async fn read_all_id() -> impl IntoResponse { + match User::read_all_id().await { Ok(user_ids) => (StatusCode::OK, Json(serde_json::json!(user_ids))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -210,11 +186,8 @@ async fn read_all_id(State(app_state): State) -> impl IntoResponse { } } -async fn read_all_id_for_name( - State(app_state): State, - Path(name): Path, -) -> impl IntoResponse { - match User::read_all_id_for_name(&name, &app_state.database_connection).await { +async fn read_all_id_for_name(Path(name): Path) -> impl IntoResponse { + match User::read_all_id_for_name(&name).await { Ok(user_ids) => (StatusCode::OK, Json(serde_json::json!(user_ids))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -223,11 +196,8 @@ async fn read_all_id_for_name( } } -async fn read_all_id_for_surname( - State(app_state): State, - Path(surname): Path, -) -> impl IntoResponse { - match User::read_all_id_for_surname(&surname, &app_state.database_connection).await { +async fn read_all_id_for_surname(Path(surname): Path) -> impl IntoResponse { + match User::read_all_id_for_surname(&surname).await { Ok(user_ids) => (StatusCode::OK, Json(serde_json::json!(user_ids))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -236,11 +206,8 @@ async fn read_all_id_for_surname( } } -async fn read_all_id_for_birth_date( - State(app_state): State, - Path(birth_date): Path, -) -> impl IntoResponse { - match User::read_all_id_for_birth_date(&birth_date, &app_state.database_connection).await { +async fn read_all_id_for_birth_date(Path(birth_date): Path) -> impl IntoResponse { + match User::read_all_id_for_birth_date(&birth_date).await { Ok(user_ids) => (StatusCode::OK, Json(serde_json::json!(user_ids))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -249,11 +216,8 @@ async fn read_all_id_for_birth_date( } } -async fn read_all_id_for_role( - State(app_state): State, - Path(role_id): Path, -) -> impl IntoResponse { - match User::read_all_id_for_role(&role_id, &app_state.database_connection).await { +async fn read_all_id_for_role(Path(role_id): Path) -> impl IntoResponse { + match User::read_all_id_for_role(&role_id).await { Ok(user_ids) => (StatusCode::OK, Json(serde_json::json!(user_ids))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -262,11 +226,8 @@ async fn read_all_id_for_role( } } -async fn read_all_id_for_gender( - State(app_state): State, - Path(gender): Path, -) -> impl IntoResponse { - match User::read_all_id_for_gender(&gender, &app_state.database_connection).await { +async fn read_all_id_for_gender(Path(gender): Path) -> impl IntoResponse { + match User::read_all_id_for_gender(&gender).await { Ok(user_ids) => (StatusCode::OK, Json(serde_json::json!(user_ids))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -275,8 +236,8 @@ async fn read_all_id_for_gender( } } -async fn count_all(State(app_state): State) -> impl IntoResponse { - match User::count_all(&app_state.database_connection).await { +async fn count_all() -> impl IntoResponse { + match User::count_all().await { Ok(count) => (StatusCode::OK, Json(serde_json::json!(count))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -285,11 +246,8 @@ async fn count_all(State(app_state): State) -> impl IntoResponse { } } -async fn count_all_for_name( - State(app_state): State, - Path(name): Path, -) -> impl IntoResponse { - match User::count_all_for_name(&name, &app_state.database_connection).await { +async fn count_all_for_name(Path(name): Path) -> impl IntoResponse { + match User::count_all_for_name(&name).await { Ok(count) => (StatusCode::OK, Json(serde_json::json!(count))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -298,11 +256,8 @@ async fn count_all_for_name( } } -async fn count_all_for_surname( - State(app_state): State, - Path(surname): Path, -) -> impl IntoResponse { - match User::count_all_for_surname(&surname, &app_state.database_connection).await { +async fn count_all_for_surname(Path(surname): Path) -> impl IntoResponse { + match User::count_all_for_surname(&surname).await { Ok(count) => (StatusCode::OK, Json(serde_json::json!(count))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -311,11 +266,8 @@ async fn count_all_for_surname( } } -async fn count_all_for_birth_date( - State(app_state): State, - Path(birth_date): Path, -) -> impl IntoResponse { - match User::count_all_for_birth_date(&birth_date, &app_state.database_connection).await { +async fn count_all_for_birth_date(Path(birth_date): Path) -> impl IntoResponse { + match User::count_all_for_birth_date(&birth_date).await { Ok(count) => (StatusCode::OK, Json(serde_json::json!(count))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -324,11 +276,8 @@ async fn count_all_for_birth_date( } } -async fn count_all_for_role( - State(app_state): State, - Path(role_id): Path, -) -> impl IntoResponse { - match User::count_all_for_role(&role_id, &app_state.database_connection).await { +async fn count_all_for_role(Path(role_id): Path) -> impl IntoResponse { + match User::count_all_for_role(&role_id).await { Ok(count) => (StatusCode::OK, Json(serde_json::json!(count))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -337,11 +286,8 @@ async fn count_all_for_role( } } -async fn count_all_for_gender( - State(app_state): State, - Path(gender): Path, -) -> impl IntoResponse { - match User::count_all_for_gender(&gender, &app_state.database_connection).await { +async fn count_all_for_gender(Path(gender): Path) -> impl IntoResponse { + match User::count_all_for_gender(&gender).await { Ok(count) => (StatusCode::OK, Json(serde_json::json!(count))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/routing/user_contact.rs b/src/routing/user_contact.rs index de5397a..4478c27 100644 --- a/src/routing/user_contact.rs +++ b/src/routing/user_contact.rs @@ -1,5 +1,5 @@ use axum::{ - extract::{Path, State}, + extract::Path, http::StatusCode, response::IntoResponse, routing::{delete, get, patch, post}, @@ -7,7 +7,7 @@ use axum::{ }; use serde::{Deserialize, Serialize}; -use crate::{feature::user_contact::UserContact, AppState}; +use crate::feature::user_contact::UserContact; #[derive(Debug, Serialize, Deserialize)] struct CreateUserContact { @@ -21,7 +21,7 @@ struct UpdateUserContact { pub contact_id: i64, } -pub fn route(State(app_state): State) -> Router { +pub fn route() -> Router { Router::new() .route("/", post(create)) .route("/roles/:user_id/contacts/:contact_id", get(read)) @@ -29,17 +29,12 @@ pub fn route(State(app_state): State) -> Router { .route("/roles/:user_id/contacts/:contact_id", delete(delete_)) .route("/users/:user_id", get(read_all_for_user)) .route("/users/:user_id", delete(delete_all_for_user)) - .with_state(app_state) } -async fn create( - State(app_state): State, - Json(create_user_contact): Json, -) -> impl IntoResponse { +async fn create(Json(create_user_contact): Json) -> impl IntoResponse { match UserContact::create( &create_user_contact.user_id, &create_user_contact.contact_id, - &app_state.database_connection, ) .await { @@ -51,11 +46,8 @@ async fn create( } } -async fn read( - State(app_state): State, - Path((user_id, contact_id)): Path<(i64, i64)>, -) -> impl IntoResponse { - match UserContact::read(&user_id, &contact_id, &app_state.database_connection).await { +async fn read(Path((user_id, contact_id)): Path<(i64, i64)>) -> impl IntoResponse { + match UserContact::read(&user_id, &contact_id).await { Ok(user_contact) => (StatusCode::OK, Json(serde_json::json!(user_contact))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -64,17 +56,8 @@ async fn read( } } -async fn update( - State(app_state): State, - Json(update_role): Json, -) -> impl IntoResponse { - match UserContact::update( - &update_role.user_id, - &update_role.contact_id, - &app_state.database_connection, - ) - .await - { +async fn update(Json(update_role): Json) -> impl IntoResponse { + match UserContact::update(&update_role.user_id, &update_role.contact_id).await { Ok(user_contact) => (StatusCode::ACCEPTED, Json(serde_json::json!(user_contact))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -83,11 +66,8 @@ async fn update( } } -async fn delete_( - State(app_state): State, - Path((user_id, contact_id)): Path<(i64, i64)>, -) -> impl IntoResponse { - match UserContact::delete(&user_id, &contact_id, &app_state.database_connection).await { +async fn delete_(Path((user_id, contact_id)): Path<(i64, i64)>) -> impl IntoResponse { + match UserContact::delete(&user_id, &contact_id).await { Ok(user_contact) => ( StatusCode::NO_CONTENT, Json(serde_json::json!(user_contact)), @@ -99,11 +79,8 @@ async fn delete_( } } -async fn read_all_for_user( - State(app_state): State, - Path(user_id): Path, -) -> impl IntoResponse { - match UserContact::read_all_for_user(&user_id, &app_state.database_connection).await { +async fn read_all_for_user(Path(user_id): Path) -> impl IntoResponse { + match UserContact::read_all_for_user(&user_id).await { Ok(role_contacts) => (StatusCode::OK, Json(serde_json::json!(role_contacts))), Err(err_val) => ( StatusCode::BAD_REQUEST, @@ -112,11 +89,8 @@ async fn read_all_for_user( } } -async fn delete_all_for_user( - State(app_state): State, - Path(user_id): Path, -) -> impl IntoResponse { - match UserContact::delete_all_for_user(&user_id, &app_state.database_connection).await { +async fn delete_all_for_user(Path(user_id): Path) -> impl IntoResponse { + match UserContact::delete_all_for_user(&user_id).await { Ok(role_contacts) => (StatusCode::OK, Json(serde_json::json!(role_contacts))), Err(err_val) => ( StatusCode::BAD_REQUEST, diff --git a/src/server.rs b/src/server.rs index 187be6f..46793db 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,16 +1,11 @@ use tokio::net::TcpListener; -use crate::{AppState, SERVER_CONFIG}; +use crate::SERVER_CONFIG; -pub async fn start_server(app_state: AppState) { - let server_config = &SERVER_CONFIG; +pub async fn start_server() { + let router = crate::routing::route(&SERVER_CONFIG.concurrency_limit).await; + let listener = TcpListener::bind(&SERVER_CONFIG.address).await.unwrap(); - let router = crate::routing::route( - &server_config.concurrency_limit, - axum::extract::State(app_state), - ) - .await; - let listener = TcpListener::bind(&server_config.address).await.unwrap(); - println!("\n\thttp://{}", server_config.address); + println!("\n\thttp://{}", &SERVER_CONFIG.address); axum::serve(listener, router).await.unwrap() }