Added accounts API.

This commit is contained in:
2026-09-27 10:26:11 +02:00
parent 5f4c9bdf90
commit 4e1eea5849
18 changed files with 540 additions and 0 deletions
+101
View File
@@ -0,0 +1,101 @@
use axum::{extract::State, http::StatusCode};
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;
use super::{
dtos::{AccountRequest, AccountResponse},
extractors::{json::Json, path::Path, query::Query},
};
use crate::{
error::AppError,
repository::{
accounts as repository,
dtos::{Delete, Upsert},
},
};
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new()
.route("/", axum::routing::get(query_accounts))
.route(
"/{id}",
axum::routing::get(get_account)
.put(upsert_account)
.delete(delete_account),
)
}
#[derive(Debug, Deserialize)]
pub struct QueryParams {
pub limit: Option<u64>,
pub offset: Option<u64>,
}
impl TryFrom<QueryParams> for repository::Query {
type Error = AppError;
fn try_from(query: QueryParams) -> Result<Self, Self::Error> {
Ok(repository::Query {
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
})
}
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn query_accounts(
State(pool): State<PgPool>,
Query(query): Query<QueryParams>,
) -> Result<Json<Vec<AccountResponse>>, AppError> {
let accounts = repository::list(&pool, query.try_into()?)
.await?
.into_iter()
.map(AccountResponse::from)
.collect();
Ok(Json(accounts))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn get_account(
State(pool): State<PgPool>,
Path(id): Path<Uuid>,
) -> Result<Json<AccountResponse>, AppError> {
let account = repository::get(&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<PgPool>,
Path(id): Path<Uuid>,
Json(account): Json<AccountRequest>,
) -> Result<(StatusCode, Json<AccountResponse>), AppError> {
let account = account.into_domain(id)?;
let (status, account) = match repository::upsert(&pool, account).await? {
Upsert::Created(account) => (StatusCode::CREATED, account),
Upsert::Updated(account) => (StatusCode::OK, account),
};
Ok((status, Json(account.into())))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn delete_account(
Path(id): Path<Uuid>,
State(pool): State<PgPool>,
) -> Result<StatusCode, AppError> {
match repository::delete(&pool, id).await? {
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
Delete::NotFound => Err(AppError::NotFound),
}
}