Skip to content

Commit

Permalink
do some cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
ns_lukyanenko committed Jan 22, 2024
1 parent 8e46120 commit 1a65fc4
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 74 deletions.
12 changes: 6 additions & 6 deletions src/controllers/product.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
pub async fn create_product(
State(state): State<Arc<AppState>>,
Json(payload): Json<CreateProduct>,
) -> Result<(), (StatusCode, String)> {
) -> Result<impl IntoResponse, (StatusCode, String)> {
product_service::create_product(payload, state).await?;

Ok(())
Ok(Json({}))
}

pub async fn get_product_list(
Expand All @@ -27,17 +27,17 @@ pub async fn get_product_list(
pub async fn update_product(
State(state): State<Arc<AppState>>,
Json(payload): Json<UpdateProduct>,
) -> Result<(), (StatusCode, String)> {
) -> Result<impl IntoResponse, (StatusCode, String)> {
product_service::update_product(payload, state).await?;

Ok(())
Ok(Json({}))
}

pub async fn delete_product(
State(state): State<Arc<AppState>>,
Json(payload): Json<ProductDelete>,
) -> Result<(), (StatusCode, String)> {
) -> Result<impl IntoResponse, (StatusCode, String)> {
product_service::delete_product(payload.id, state).await?;

Ok(())
Ok(Json({}))
}
73 changes: 5 additions & 68 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,19 @@
mod config;
mod controllers;
mod middlewares;
mod router;
mod services;
mod structs;
mod utils;

use std::sync::Arc;

use axum::{
body::Body,
http::{
header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
HeaderValue, Method,
},
middleware,
routing::{delete, get, patch, post, put},
Router,
};
use config::Config;
use controllers::auth::{login, register};
use dotenv::dotenv;
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
use tokio::signal;
use tower_http::{cors::CorsLayer, trace::TraceLayer};
use std::sync::Arc;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use utils::graceful_shutdown::shutdown_signal;

use crate::controllers::product::{
create_product, delete_product, get_product_list, update_product,
};
use crate::router::router::create_router;

pub struct AppState {
db: Pool<Postgres>,
Expand Down Expand Up @@ -63,32 +49,7 @@ async fn main() -> Result<(), sqlx::Error> {
env: config.clone(),
});

let user_routes = Router::new()
.route("/register", post(register))
.route("/login", post(login));

let products_routes = Router::new()
.route("/create", put(create_product))
.route("/get_list", get(get_product_list))
.route("/update", patch(update_product))
.route("/delete", delete(delete_product))
.route_layer(middleware::from_fn_with_state(
app_state.clone(),
middlewares::auth::auth::<Body>,
));

let cors = CorsLayer::new()
.allow_origin("http://localhost:8080".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
.allow_credentials(true)
.allow_headers([AUTHORIZATION, ACCEPT, CONTENT_TYPE]);

let app = Router::new()
.nest("/users", user_routes)
.nest("/products", products_routes)
.layer(cors)
.layer(TraceLayer::new_for_http())
.with_state(app_state);
let app = create_router(app_state);

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("🚀 Server started successfully");
Expand All @@ -100,27 +61,3 @@ async fn main() -> Result<(), sqlx::Error> {

Ok(())
}

async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = std::future::pending::<()>();

tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
1 change: 1 addition & 0 deletions src/router/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod router;
50 changes: 50 additions & 0 deletions src/router/router.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use std::sync::Arc;

use axum::{
body::Body,
http::{
header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
HeaderValue, Method,
},
middleware,
routing::{delete, get, patch, post, put},
Router,
};
use tower_http::{cors::CorsLayer, trace::TraceLayer};

use crate::{
controllers::{
auth::{login, register},
product::{create_product, delete_product, get_product_list, update_product},
},
middlewares, AppState,
};

pub fn create_router(app_state: Arc<AppState>) -> Router {
let user_routes = Router::new()
.route("/register", post(register))
.route("/login", post(login));

let products_routes = Router::new()
.route("/create", put(create_product))
.route("/get_list", get(get_product_list))
.route("/update", patch(update_product))
.route("/delete", delete(delete_product))
.route_layer(middleware::from_fn_with_state(
app_state.clone(),
middlewares::auth::auth::<Body>,
));

let cors = CorsLayer::new()
.allow_origin("http://localhost:8080".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
.allow_credentials(true)
.allow_headers([AUTHORIZATION, ACCEPT, CONTENT_TYPE]);

Router::new()
.nest("/users", user_routes)
.nest("/products", products_routes)
.layer(cors)
.layer(TraceLayer::new_for_http())
.with_state(app_state)
}
25 changes: 25 additions & 0 deletions src/utils/graceful_shutdown.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use tokio::signal;

pub async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = std::future::pending::<()>();

tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod connection;
pub mod graceful_shutdown;

0 comments on commit 1a65fc4

Please sign in to comment.