Skip to content

Commit

Permalink
Merge pull request #4 from valentin994/review-routes
Browse files Browse the repository at this point in the history
Review routes
  • Loading branch information
valentin994 authored May 31, 2024
2 parents 3a7f5ea + 79bd878 commit 50cb5ad
Show file tree
Hide file tree
Showing 14 changed files with 571 additions and 11 deletions.
16 changes: 14 additions & 2 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jobs:
postgres:
image: postgres
env:
POSTGRES_HOST: postgres
POSTGRES_PASSWORD: mysecretpassword
options: >-
--health-cmd pg_isready
Expand All @@ -37,9 +38,20 @@ jobs:
- 5432:5432
steps:
- uses: actions/checkout@v4
- name: Build and run API
- uses: dtolnay/rust-toolchain@stable
- name: Migrate Database
env:
DATABASE_URL: postgres://postgres:mysecretpassword@localhost:5432
run: |
cd backend
cargo install sqlx-cli --features postgres
sqlx migrate run
- name: Build and run API
env:
DATABASE_URL: postgres://postgres:[email protected]:5432
run: |
cd backend
cargo run & cargo test
cargo build
cargo sqlx prepare
cargo run &
cargo test

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ authors = ["Valentin Vareskic <[email protected]>"]

[dependencies]
axum = "0.7.5"
reqwest = "0.12.3"
reqwest = { version = "0.12.3", features = ["json"] }
serde = { version = "1.0.197", features = ["derive"] }
tokio = { version = "1.37.0", features = ["full"] }
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
sqlx = { version = "0.7", features = [ "runtime-tokio", "tls-native-tls", "any", "postgres" , "migrate" , "chrono"] }
serde_json = "1.0.117"
35 changes: 35 additions & 0 deletions backend/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::Json;
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
InternalServerError,
BodyParsingError(String),
MissingResource(String),
}

pub fn internal_error<E>(_err: E) -> AppError {
AppError::InternalServerError
}

impl IntoResponse for AppError {
fn into_response(self) -> axum::response::Response {
let (status, err_msg) = match self {
Self::InternalServerError => (
StatusCode::INTERNAL_SERVER_ERROR,
String::from("Internal Server Error"),
),
Self::BodyParsingError(message) => (
StatusCode::BAD_REQUEST,
format!("Bad request error: {}", message),
),
Self::MissingResource(message) => (
StatusCode::NOT_FOUND,
format!("Resource can't be found: {}", message),
),
};
(status, Json(json!({ "message": err_msg }))).into_response()
}
}
2 changes: 2 additions & 0 deletions backend/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod error;
pub mod routes;
27 changes: 22 additions & 5 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
use axum::{routing::get, Router};
use axum::{response::IntoResponse, routing::get, Router};
use reqwest::StatusCode;
use routes::reviews::review_router;
use sqlx::{migrate::Migrator, postgres::PgPoolOptions};
use std::time::Duration;
use tokio::net::TcpListener;

mod error;
pub mod routes;

use error::internal_error;

const DB_MAX_CONNECTIONS: u32 = 10;
const DB_CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
static MIGRATOR: Migrator = sqlx::migrate!();
Expand All @@ -16,6 +23,7 @@ async fn main() {
// initialize database
let db_connection_str = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:mysecretpassword@db:5432".to_string());
tracing::info!("Database URL: {:?}", &db_connection_str);
let pool = PgPoolOptions::new()
.max_connections(DB_MAX_CONNECTIONS)
.acquire_timeout(DB_CONNECTION_TIMEOUT)
Expand All @@ -25,19 +33,28 @@ async fn main() {

MIGRATOR.run(&pool).await.unwrap();
tracing::debug!("Database initialized and migrated");

// build our application with a route
let app = Router::new()
// `GET /` goes to `root`
.route("/", get(root))
.with_state(pool);
.nest("/review", review_router(pool).await)
.fallback(handler_404);
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
axum::serve(listener, app)
.await
.map_err(internal_error)
.unwrap();
}

// basic handler that responds with a static string
async fn root() -> &'static str {
tracing::debug!("hello");
"Hello, World!"
}

async fn handler_404() -> impl IntoResponse {
(
StatusCode::NOT_FOUND,
"The requested resource was not found",
)
}
1 change: 1 addition & 0 deletions backend/src/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod reviews;
Loading

0 comments on commit 50cb5ad

Please sign in to comment.