Moved domain logic out of the database layer, to the user app route.
This commit is contained in:
@@ -9,10 +9,7 @@ use super::{
|
||||
};
|
||||
use crate::{
|
||||
error::AppError,
|
||||
repository::{
|
||||
self,
|
||||
dtos::{Delete, Upsert},
|
||||
},
|
||||
repository::{self, ReferenceRelation, RepositoryError},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
@@ -60,8 +57,9 @@ async fn get_user_app(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Json<UserAppResponse>, AppError> {
|
||||
let app = repository::user_apps::get_by_id(&pool, user_id, app_id)
|
||||
let app = repository::user_apps::get_by_id(&pool, app_id)
|
||||
.await?
|
||||
.filter(|app| app.user_id == user_id)
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(app.into()))
|
||||
@@ -75,14 +73,28 @@ async fn upsert_user_app(
|
||||
Json(request): Json<UserAppRequest>,
|
||||
) -> Result<(StatusCode, Json<UserAppResponse>), AppError> {
|
||||
let app = request.into_domain(user_id, app_id);
|
||||
let upsert = repository::user_apps::upsert(&pool, app).await?;
|
||||
|
||||
let (status, app) = match upsert {
|
||||
Upsert::Created(app) => (StatusCode::CREATED, app),
|
||||
Upsert::Updated(app) => (StatusCode::OK, app),
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
let upserted = repository::user_apps::upsert(&mut *tx, app).await?;
|
||||
if upserted
|
||||
.previous
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.user_id != user_id)
|
||||
{
|
||||
return Err(RepositoryError::OwnershipConflict {
|
||||
relation: ReferenceRelation::UserApp,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
let status = if upserted.previous.is_some() {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::CREATED
|
||||
};
|
||||
|
||||
Ok((status, Json(app.into())))
|
||||
Ok((status, Json(upserted.current.into())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -91,8 +103,14 @@ async fn delete_user_app(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::user_apps::delete_by_id(&pool, user_id, app_id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
if repository::user_apps::delete_by_id(&mut *tx, app_id)
|
||||
.await?
|
||||
.is_none_or(|user_app| user_app.user_id != user_id)
|
||||
{
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user