use axum::{extract::State, http::StatusCode}; use serde::Deserialize; use sqlx::PgPool; use uuid::Uuid; use super::{ dtos::account::{AccountRequest, AccountResponse}, extractors::{json::Json, path::Path, query::Query}, }; use crate::{ error::AppError, repository::{self}, }; pub fn create_router() -> axum::Router { axum::Router::new() .route("/", axum::routing::get(list_accounts)) .route( "/{id}", axum::routing::get(get_account) .put(upsert_account) .delete(delete_account), ) } #[derive(Debug, Deserialize)] pub struct QueryParams { pub name: Option, pub limit: Option, pub offset: Option, } #[axum::debug_handler] #[tracing::instrument(skip(pool))] async fn list_accounts( State(pool): State, Query(query): Query, ) -> Result>, AppError> { let query = repository::accounts::Query { name: query.name, limit: Some(query.limit.unwrap_or(20)), offset: query.offset, }; let accounts = repository::accounts::list(&pool, query) .await? .into_iter() .map(AccountResponse::from) .collect(); Ok(Json(accounts)) } #[axum::debug_handler] #[tracing::instrument(skip(pool))] async fn get_account( State(pool): State, Path(id): Path, ) -> Result, AppError> { let account = repository::accounts::get_by_id(&pool, id) .await? .ok_or(AppError::NotFound)?; Ok(Json(account.into())) } #[axum::debug_handler] #[tracing::instrument(skip(pool, account))] async fn upsert_account( State(pool): State, Path(id): Path, Json(account): Json, ) -> Result<(StatusCode, Json), AppError> { let account = account.into_domain(id)?; let upserted = repository::accounts::upsert(&pool, account).await?; let status = if upserted.previous.is_some() { StatusCode::OK } else { StatusCode::CREATED }; Ok((status, Json(upserted.current.into()))) } #[axum::debug_handler] #[tracing::instrument(skip(pool))] async fn delete_account( Path(id): Path, State(pool): State, ) -> Result { repository::accounts::delete_by_id(&pool, id) .await? .ok_or(AppError::NotFound)?; Ok(StatusCode::NO_CONTENT) }