first
This commit is contained in:
78
src/state/data.rs
Normal file
78
src/state/data.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::Json,
|
||||
http::StatusCode,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use sqlx::PgPool;
|
||||
use crate::auth::structs::AppState; // Import AppState
|
||||
|
||||
use crate::state::structs::{County, ErrorResponse};
|
||||
|
||||
pub async fn get_counties_by_state(
|
||||
State(app_state): State<AppState>, // Changed from State<PgPool> to State<AppState>
|
||||
Path(state_abbr): Path<String>,
|
||||
) -> Result<Json<Vec<County>>, (StatusCode, Json<ErrorResponse>)> {
|
||||
let state_abbr_upper = state_abbr.to_uppercase(); // Ensure consistent casing for DB query
|
||||
println!("Querying counties for state: {}", state_abbr_upper);
|
||||
|
||||
match sqlx::query_as::<_, County>("SELECT id, name, state FROM county WHERE UPPER(state) = $1 ORDER BY name ASC")
|
||||
.bind(&state_abbr_upper)
|
||||
.fetch_all(&app_state.db) // Use app_state.db to access the pool
|
||||
.await
|
||||
{
|
||||
Ok(counties) => {
|
||||
if counties.is_empty() {
|
||||
Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ErrorResponse {
|
||||
error: format!("No counties found for state abbreviation: {}", state_abbr_upper),
|
||||
}),
|
||||
))
|
||||
} else {
|
||||
Ok(Json(counties))
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Database error fetching counties for state {}: {}", state_abbr_upper, e);
|
||||
Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Failed to retrieve counties. Please try again later.".to_string(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_county_by_id(
|
||||
State(app_state): State<AppState>,
|
||||
Path((state_abbr, county_id)): Path<(String, i32)>,
|
||||
) -> Result<Json<County>, (StatusCode, Json<ErrorResponse>)> {
|
||||
let state_abbr_upper = state_abbr.to_uppercase();
|
||||
println!("Querying county with ID: {} for state: {}", county_id, state_abbr_upper);
|
||||
|
||||
match sqlx::query_as::<_, County>("SELECT id, name, state FROM county WHERE UPPER(state) = $1 AND id = $2")
|
||||
.bind(&state_abbr_upper)
|
||||
.bind(county_id)
|
||||
.fetch_one(&app_state.db)
|
||||
.await
|
||||
{
|
||||
Ok(county) => Ok(Json(county)),
|
||||
Err(sqlx::Error::RowNotFound) => Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ErrorResponse {
|
||||
error: format!("County with ID {} not found in state {}", county_id, state_abbr_upper),
|
||||
}),
|
||||
)),
|
||||
Err(e) => {
|
||||
eprintln!("Database error fetching county with ID {} for state {}: {}", county_id, state_abbr_upper, e);
|
||||
Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Failed to retrieve county. Please try again later.".to_string(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user