feat: batch favorites endpoint + frontend dedup fixes
Backend: - Add POST /api/favorites/batch endpoint (single multi-row INSERT) - Add BatchFavoritesResult/BatchFavoritesStats DTOs - Add batch methods to ports, service, PG repository - Transaction-based insert with ON CONFLICT DO NOTHING, chunking at 5000 Frontend: - Rewrite batchFavorites() to single API call (40 requests → 1) - Add _replaceCacheFromResponse() to avoid extra GET round-trip - Centralize formatFileSize, isTextViewable, formatDateTime, formatDateShort - Remove duplicate icon mapping from app.js - Fix inconsistent quota defaults (10GB everywhere)
This commit is contained in:
@@ -78,3 +78,23 @@ impl FavoriteItemDto {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Result DTO for batch add-to-favorites.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BatchFavoritesResult {
|
||||
/// Statistics about the batch operation
|
||||
pub stats: BatchFavoritesStats,
|
||||
/// Full list of the user's favourites (enriched), so the client can
|
||||
/// replace its local cache in a single round-trip.
|
||||
pub favorites: Vec<FavoriteItemDto>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BatchFavoritesStats {
|
||||
/// How many items were requested
|
||||
pub requested: usize,
|
||||
/// How many were actually inserted (new)
|
||||
pub inserted: u64,
|
||||
/// How many were already favourites (skipped)
|
||||
pub already_existed: u64,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::dtos::favorites_dto::FavoriteItemDto;
|
||||
use crate::application::dtos::favorites_dto::{BatchFavoritesResult, FavoriteItemDto};
|
||||
use crate::common::errors::Result;
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -21,6 +21,14 @@ pub trait FavoritesUseCase: Send + Sync {
|
||||
|
||||
/// Check if an item is in user's favorites
|
||||
async fn is_favorite(&self, user_id: &str, item_id: &str, item_type: &str) -> Result<bool>;
|
||||
|
||||
/// Add multiple items to favorites in a single transaction.
|
||||
/// Returns enriched favourites list so the client can replace its cache.
|
||||
async fn batch_add_to_favorites(
|
||||
&self,
|
||||
user_id: &str,
|
||||
items: &[(String, String)],
|
||||
) -> Result<BatchFavoritesResult>;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────
|
||||
@@ -45,4 +53,12 @@ pub trait FavoritesRepositoryPort: Send + Sync + 'static {
|
||||
|
||||
/// Checks if an item is in favorites.
|
||||
async fn is_favorite(&self, user_id: &str, item_id: &str, item_type: &str) -> Result<bool>;
|
||||
|
||||
/// Insert multiple items in a single transaction.
|
||||
/// Returns the number of rows actually inserted (ignoring duplicates).
|
||||
async fn add_favorites_batch(
|
||||
&self,
|
||||
user_id: &str,
|
||||
items: &[(String, String)],
|
||||
) -> Result<u64>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::application::dtos::favorites_dto::FavoriteItemDto;
|
||||
use crate::application::dtos::favorites_dto::{BatchFavoritesResult, BatchFavoritesStats, FavoriteItemDto};
|
||||
use crate::application::ports::favorites_ports::{FavoritesRepositoryPort, FavoritesUseCase};
|
||||
use crate::common::errors::{DomainError, ErrorKind, Result};
|
||||
use async_trait::async_trait;
|
||||
@@ -94,4 +94,51 @@ impl FavoritesUseCase for FavoritesService {
|
||||
);
|
||||
self.repo.is_favorite(user_id, item_id, item_type).await
|
||||
}
|
||||
|
||||
async fn batch_add_to_favorites(
|
||||
&self,
|
||||
user_id: &str,
|
||||
items: &[(String, String)],
|
||||
) -> Result<BatchFavoritesResult> {
|
||||
info!(
|
||||
"Batch adding {} items to favorites for user {}",
|
||||
items.len(),
|
||||
user_id
|
||||
);
|
||||
|
||||
// Validate all item types
|
||||
for (item_id, item_type) in items {
|
||||
if item_type != "file" && item_type != "folder" {
|
||||
return Err(DomainError::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"Favorites",
|
||||
format!(
|
||||
"Item type must be 'file' or 'folder' for item '{}'",
|
||||
item_id
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let requested = items.len();
|
||||
let inserted = self.repo.add_favorites_batch(user_id, items).await?;
|
||||
let already_existed = requested as u64 - inserted;
|
||||
|
||||
info!(
|
||||
"Batch favorites for user {}: {} requested, {} inserted, {} already existed",
|
||||
user_id, requested, inserted, already_existed
|
||||
);
|
||||
|
||||
// Return the full enriched list so the client can replace its cache
|
||||
let favorites = self.repo.get_favorites(user_id).await?;
|
||||
|
||||
Ok(BatchFavoritesResult {
|
||||
stats: BatchFavoritesStats {
|
||||
requested,
|
||||
inserted,
|
||||
already_existed,
|
||||
},
|
||||
favorites,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,4 +162,91 @@ impl FavoritesRepositoryPort for FavoritesPgRepository {
|
||||
|
||||
Ok(row.try_get("is_favorite").unwrap_or(false))
|
||||
}
|
||||
|
||||
async fn add_favorites_batch(
|
||||
&self,
|
||||
user_id: &str,
|
||||
items: &[(String, String)],
|
||||
) -> Result<u64> {
|
||||
if items.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let user_uuid = Uuid::parse_str(user_id)?;
|
||||
|
||||
// Validate all item_types upfront
|
||||
for (_, item_type) in items {
|
||||
if item_type != "file" && item_type != "folder" {
|
||||
return Err(DomainError::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"Favorites",
|
||||
format!("Item type must be 'file' or 'folder', got '{}'", item_type),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Build a multi-row INSERT with ON CONFLICT DO NOTHING
|
||||
// Using a single transaction for atomicity
|
||||
let mut tx = self.db_pool.begin().await.map_err(|e| {
|
||||
error!("Database error starting transaction: {}", e);
|
||||
DomainError::new(
|
||||
ErrorKind::InternalError,
|
||||
"Favorites",
|
||||
format!("Failed to start transaction: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut total_inserted: u64 = 0;
|
||||
|
||||
// Insert in chunks to stay within Postgres' parameter limit (max ~32k params)
|
||||
for chunk in items.chunks(5000) {
|
||||
let mut query = String::from(
|
||||
"INSERT INTO auth.user_favorites (user_id, item_id, item_type) VALUES ",
|
||||
);
|
||||
let mut param_idx = 1u32;
|
||||
let mut first = true;
|
||||
|
||||
for _ in chunk {
|
||||
if !first {
|
||||
query.push_str(", ");
|
||||
}
|
||||
query.push_str(&format!(
|
||||
"(${}::TEXT, ${}, ${})",
|
||||
param_idx,
|
||||
param_idx + 1,
|
||||
param_idx + 2
|
||||
));
|
||||
param_idx += 3;
|
||||
first = false;
|
||||
}
|
||||
query.push_str(" ON CONFLICT (user_id, item_id, item_type) DO NOTHING");
|
||||
|
||||
let mut q = sqlx::query(&query);
|
||||
for (item_id, item_type) in chunk {
|
||||
q = q.bind(&user_uuid).bind(item_id).bind(item_type);
|
||||
}
|
||||
|
||||
let result = q.execute(&mut *tx).await.map_err(|e| {
|
||||
error!("Database error in batch insert favorites: {}", e);
|
||||
DomainError::new(
|
||||
ErrorKind::InternalError,
|
||||
"Favorites",
|
||||
format!("Failed to batch insert favorites: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
total_inserted += result.rows_affected();
|
||||
}
|
||||
|
||||
tx.commit().await.map_err(|e| {
|
||||
error!("Database error committing batch favorites: {}", e);
|
||||
DomainError::new(
|
||||
ErrorKind::InternalError,
|
||||
"Favorites",
|
||||
format!("Failed to commit batch favorites: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(total_inserted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
};
|
||||
use axum::{Json, extract::{Path, State}, http::StatusCode, response::IntoResponse};
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::application::ports::favorites_ports::FavoritesUseCase;
|
||||
use crate::interfaces::middleware::auth::AuthUser;
|
||||
|
||||
/// Single item in a batch-add-favorites request.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BatchFavoriteItem {
|
||||
pub item_id: String,
|
||||
pub item_type: String,
|
||||
}
|
||||
|
||||
/// Request body for POST /api/favorites/batch
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BatchFavoritesRequest {
|
||||
pub items: Vec<BatchFavoriteItem>,
|
||||
}
|
||||
|
||||
/// Handler for favorite-related API endpoints
|
||||
pub async fn get_favorites(
|
||||
State(favorites_service): State<Arc<dyn FavoritesUseCase>>,
|
||||
@@ -120,3 +129,63 @@ pub async fn remove_favorite(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add multiple items to favourites in a single transaction.
|
||||
/// POST /api/favorites/batch
|
||||
pub async fn batch_add_favorites(
|
||||
State(favorites_service): State<Arc<dyn FavoritesUseCase>>,
|
||||
auth_user: AuthUser,
|
||||
Json(body): Json<BatchFavoritesRequest>,
|
||||
) -> impl IntoResponse {
|
||||
let user_id = &auth_user.id;
|
||||
|
||||
if body.items.is_empty() {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({ "error": "items array must not be empty" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Validate item types
|
||||
for item in &body.items {
|
||||
if item.item_type != "file" && item.item_type != "folder" {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("Item type must be 'file' or 'folder', got '{}'", item.item_type)
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
let items: Vec<(String, String)> = body
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|i| (i.item_id, i.item_type))
|
||||
.collect();
|
||||
|
||||
match favorites_service
|
||||
.batch_add_to_favorites(user_id, &items)
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
info!(
|
||||
"Batch favourites: {} requested, {} inserted, {} already existed",
|
||||
result.stats.requested, result.stats.inserted, result.stats.already_existed
|
||||
);
|
||||
(StatusCode::OK, Json(serde_json::json!(result))).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Error in batch add favorites: {}", err);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("Failed to batch add favorites: {}", err)
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,6 +231,7 @@ pub fn create_api_routes(app_state: &AppState) -> Router<AppState> {
|
||||
|
||||
Router::new()
|
||||
.route("/", get(favorites_handler::get_favorites))
|
||||
.route("/batch", post(favorites_handler::batch_add_favorites))
|
||||
.route(
|
||||
"/{item_type}/{item_id}",
|
||||
post(favorites_handler::add_favorite),
|
||||
|
||||
Reference in New Issue
Block a user