fix: harden favorite state consistency
This commit is contained in:
@@ -65,49 +65,31 @@ pub async fn upsert_product(
|
||||
user_id: Uuid,
|
||||
product_id: Uuid,
|
||||
) -> ApiResult<Uuid> {
|
||||
let inserted: Option<Uuid> = sqlx::query_scalar(
|
||||
Ok(sqlx::query_scalar(
|
||||
"INSERT INTO favorites (user_id, product_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (user_id, product_id) WHERE product_id IS NOT NULL
|
||||
DO NOTHING
|
||||
DO UPDATE SET created_at = favorites.created_at
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(product_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some(id) = inserted {
|
||||
return Ok(id);
|
||||
}
|
||||
sqlx::query_scalar("SELECT id FROM favorites WHERE user_id = $1 AND product_id = $2")
|
||||
.bind(user_id)
|
||||
.bind(product_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("favorite".into()))
|
||||
.fetch_one(&mut *tx)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn upsert_shop(tx: &mut PgConnection, user_id: Uuid, shop_id: Uuid) -> ApiResult<Uuid> {
|
||||
let inserted: Option<Uuid> = sqlx::query_scalar(
|
||||
Ok(sqlx::query_scalar(
|
||||
"INSERT INTO favorites (user_id, shop_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (user_id, shop_id) WHERE shop_id IS NOT NULL
|
||||
DO NOTHING
|
||||
DO UPDATE SET created_at = favorites.created_at
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(shop_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some(id) = inserted {
|
||||
return Ok(id);
|
||||
}
|
||||
sqlx::query_scalar("SELECT id FROM favorites WHERE user_id = $1 AND shop_id = $2")
|
||||
.bind(user_id)
|
||||
.bind(shop_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("favorite".into()))
|
||||
.fetch_one(&mut *tx)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn delete_product(db: &PgPool, user_id: Uuid, product_id: Uuid) -> ApiResult<()> {
|
||||
|
||||
Reference in New Issue
Block a user