Rewrite the use of unwrap() to use Result<>

This commit is contained in:
2025-11-30 18:08:01 +03:00
parent 264a45acf9
commit 499987a465
9 changed files with 48 additions and 40 deletions

2
.gitignore vendored
View File

@ -1,6 +1,8 @@
# my gitignore # my gitignore
todo.md todo.md
.env .env
trash/
.cargo/
# ---> Rust # ---> Rust
# Generated by Cargo # Generated by Cargo

4
Cargo.lock generated
View File

@ -31,9 +31,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]] [[package]]
name = "axum" name = "axum"
version = "0.8.6" version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a18ed336352031311f4e0b4dd2ff392d4fbb370777c9d18d7fc9d7359f73871" checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425"
dependencies = [ dependencies = [
"axum-core", "axum-core",
"bytes", "bytes",

View File

@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
axum = "0.8.6" axum = "0.8.7"
dotenvy = "0.15.7" dotenvy = "0.15.7"
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio"] } sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio"] }

View File

@ -1,5 +1,5 @@
services: services:
database: postgres:
image: docker.io/postgres:17 image: docker.io/postgres:17
environment: environment:
POSTGRES_DB: ${POSTGRES_DB} POSTGRES_DB: ${POSTGRES_DB}
@ -7,3 +7,7 @@ services:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
ports: ports:
- ${POSTGRES_PORT}:5432 - ${POSTGRES_PORT}:5432
adminer:
image: docker.io/adminer
ports:
- 8080:8080

View File

@ -1,2 +1 @@
-- Add down migration script here
DROP TABLE games; DROP TABLE games;

View File

@ -1,5 +1,3 @@
-- Add up migration script here
CREATE TABLE games( CREATE TABLE games(
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name TEXT NOT NULL, name TEXT NOT NULL,

View File

@ -1,28 +1,25 @@
use sqlx::PgPool;
use std::env; use std::env;
use sqlx::PgPool; pub async fn create_pool() -> Result<PgPool, axum::BoxError> {
PgPool::connect(&database_url()?).await.map_err(Into::into)
pub async fn create_pool() -> PgPool {
PgPool::connect(&database_url())
.await
.expect("Could not connect to database")
} }
fn database_url() -> String { fn database_url() -> Result<String, axum::BoxError> {
let _ = dotenvy::dotenv(); let _ = dotenvy::dotenv();
let database_url = format!( let database_url = format!(
"postgres://{}:{}@{}:{}/{}", "postgres://{}:{}@{}:{}/{}",
env::var("POSTGRES_USER").unwrap(), env::var("POSTGRES_USER")?,
env::var("POSTGRES_PASSWORD").unwrap(), env::var("POSTGRES_PASSWORD")?,
env::var("POSTGRES_HOST").unwrap(), env::var("POSTGRES_HOST")?,
env::var("POSTGRES_PORT").unwrap(), env::var("POSTGRES_PORT")?,
env::var("POSTGRES_DB").unwrap(), env::var("POSTGRES_DB")?,
); );
if database_url != env::var("DATABASE_URL").unwrap() { if database_url != env::var("DATABASE_URL")? {
panic!("DATABASE_URL is not set correctly"); return Err("DATABASE_URL is not set correctly".into());
} }
println!("DATABASE_URL={database_url}"); println!("DATABASE_URL={}", database_url);
database_url Ok(database_url)
} }

View File

@ -1,3 +1,4 @@
#![warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use tokio::net::TcpListener; use tokio::net::TcpListener;
mod app_state; mod app_state;
@ -8,17 +9,19 @@ mod router;
use app_state::AppState; use app_state::AppState;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() -> Result<(), axum::BoxError> {
let state = AppState { let state = AppState {
pool: database::create_pool().await, pool: database::create_pool().await?,
}; };
sqlx::migrate!().run(&state.pool).await.unwrap(); sqlx::migrate!().run(&state.pool).await?;
let addr = "127.0.0.1:8000"; let addr = "127.0.0.1:8000";
let listener = TcpListener::bind(addr).await.unwrap(); let listener = TcpListener::bind(addr).await?;
println!("Listening at {addr}"); println!("Listening at {addr}");
axum::serve(listener, router::router(state)).await.unwrap(); axum::serve(listener, router::router(state)).await?;
Ok(())
} }

View File

@ -3,7 +3,7 @@ use axum::routing::{get, post};
use axum::{ use axum::{
Json, Json,
extract::{Path, State}, extract::{Path, State},
response::IntoResponse, http::StatusCode,
}; };
use crate::app_state::AppState; use crate::app_state::AppState;
@ -16,19 +16,19 @@ pub fn router(state: AppState) -> axum::Router {
.with_state(state) .with_state(state)
} }
pub async fn games_list(State(state): State<AppState>) -> impl IntoResponse { pub async fn games_list(State(state): State<AppState>) -> Result<Json<Vec<Game>>, StatusCode> {
let games: Vec<Game> = sqlx::query_file_as!(Game, "queries/get_all.sql") let games: Vec<Game> = sqlx::query_file_as!(Game, "queries/get_all.sql")
.fetch_all(&state.pool) .fetch_all(&state.pool)
.await .await
.unwrap(); .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Json(games) Ok(Json(games))
} }
pub async fn insert_game( pub async fn insert_game(
State(state): State<AppState>, State(state): State<AppState>,
Json(game): Json<CreateGame>, Json(game): Json<CreateGame>,
) -> impl IntoResponse { ) -> Result<StatusCode, StatusCode> {
sqlx::query_file!( sqlx::query_file!(
"queries/insert.sql", "queries/insert.sql",
game.name, game.name,
@ -40,16 +40,16 @@ pub async fn insert_game(
) )
.execute(&state.pool) .execute(&state.pool)
.await .await
.unwrap(); .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
axum::http::StatusCode::CREATED Ok(StatusCode::CREATED)
} }
pub async fn update_game( pub async fn update_game(
State(state): State<AppState>, State(state): State<AppState>,
Path(params): Path<GamePathParams>, Path(params): Path<GamePathParams>,
Json(game): Json<CreateGame>, Json(game): Json<CreateGame>,
) -> impl IntoResponse { ) -> Result<StatusCode, StatusCode> {
sqlx::query_file!( sqlx::query_file!(
"queries/update.sql", "queries/update.sql",
game.name, game.name,
@ -62,14 +62,19 @@ pub async fn update_game(
) )
.execute(&state.pool) .execute(&state.pool)
.await .await
.unwrap(); .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::OK)
} }
pub async fn delete_game(State(state): State<AppState>, Path(id): Path<i32>) -> impl IntoResponse { pub async fn delete_game(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<StatusCode, StatusCode> {
sqlx::query_file!("queries/delete.sql", id) sqlx::query_file!("queries/delete.sql", id)
.execute(&state.pool) .execute(&state.pool)
.await .await
.unwrap(); .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
axum::http::StatusCode::OK Ok(StatusCode::OK)
} }