Propagate user app ownership conflict.
This commit is contained in:
@@ -12,6 +12,22 @@ impl<T> Upsert<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub enum GuardedUpsert<T> {
|
||||
Created(T),
|
||||
Updated(T),
|
||||
Rejected,
|
||||
}
|
||||
|
||||
impl<T> GuardedUpsert<T> {
|
||||
pub fn try_map<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<GuardedUpsert<U>, E> {
|
||||
Ok(match self {
|
||||
Self::Created(value) => GuardedUpsert::Created(f(value)?),
|
||||
Self::Updated(value) => GuardedUpsert::Updated(f(value)?),
|
||||
Self::Rejected => GuardedUpsert::Rejected,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Delete {
|
||||
Deleted,
|
||||
NotFound,
|
||||
|
||||
@@ -2,7 +2,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
DatabaseError,
|
||||
dtos::{Delete, Upsert, UserAppRow},
|
||||
dtos::{Delete, GuardedUpsert, UserAppRow},
|
||||
};
|
||||
|
||||
pub struct Query {
|
||||
@@ -60,7 +60,7 @@ where
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
app: UserAppRow,
|
||||
) -> Result<Upsert<UserAppRow>, DatabaseError>
|
||||
) -> Result<GuardedUpsert<UserAppRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
@@ -70,6 +70,7 @@ where
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
id = EXCLUDED.id
|
||||
WHERE user_apps.user_id = $2
|
||||
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||
old_row.id AS "old_id?",
|
||||
new_row.id AS "id!",
|
||||
@@ -78,19 +79,23 @@ where
|
||||
app.id,
|
||||
app.user_id,
|
||||
)
|
||||
.fetch_one(executor)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
let Some(row) = row else {
|
||||
return Ok(GuardedUpsert::Rejected);
|
||||
};
|
||||
|
||||
let app = UserAppRow {
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
};
|
||||
|
||||
Ok(if row.old_id.is_some() {
|
||||
Upsert::Updated(app)
|
||||
GuardedUpsert::Updated(app)
|
||||
} else {
|
||||
Upsert::Created(app)
|
||||
GuardedUpsert::Created(app)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user