Standardized the upsert and delete pattern across the repo.
This commit is contained in:
@@ -12,10 +12,7 @@ use super::{
|
||||
use crate::{
|
||||
domain,
|
||||
error::AppError,
|
||||
repository::{
|
||||
self, RepositoryError,
|
||||
dtos::{Delete, Upsert},
|
||||
},
|
||||
repository::{self, RepositoryError},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
@@ -86,16 +83,18 @@ async fn upsert_transaction(
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
let (status, transaction) =
|
||||
match repository::transactions::upsert(&mut *tx, transaction).await? {
|
||||
Upsert::Created(transaction) => (StatusCode::CREATED, transaction),
|
||||
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||
};
|
||||
let upserted = repository::transactions::upsert(&mut *tx, transaction).await?;
|
||||
let accounts =
|
||||
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?;
|
||||
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&upserted.current)).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok((status, Json(create_response(transaction, &accounts)?)))
|
||||
let status = if upserted.previous.is_some() {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::CREATED
|
||||
};
|
||||
|
||||
Ok((status, Json(create_response(upserted.current, &accounts)?)))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -104,10 +103,11 @@ async fn delete_transaction(
|
||||
Path(id): Path<Uuid>,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::transactions::delete_by_id(&pool, id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
repository::transactions::delete_by_id(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn get_accounts_for_transactions(
|
||||
|
||||
Reference in New Issue
Block a user