98 lines
2.4 KiB
Rust
98 lines
2.4 KiB
Rust
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<PgPool> {
|
|
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<String>,
|
|
pub limit: Option<u64>,
|
|
pub offset: Option<u64>,
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn list_accounts(
|
|
State(pool): State<PgPool>,
|
|
Query(query): Query<QueryParams>,
|
|
) -> Result<Json<Vec<AccountResponse>>, 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<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<AccountResponse>, 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<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
Json(account): Json<AccountRequest>,
|
|
) -> Result<(StatusCode, Json<AccountResponse>), 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<Uuid>,
|
|
State(pool): State<PgPool>,
|
|
) -> Result<StatusCode, AppError> {
|
|
repository::accounts::delete_by_id(&pool, id)
|
|
.await?
|
|
.ok_or(AppError::NotFound)?;
|
|
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|