feat(resources): add cursor, group by on /api/favorites/resources

This commit is contained in:
Edouard Vanbelle
2026-05-28 10:08:38 +02:00
parent 5790a1459f
commit 607ae5e6df
15 changed files with 1265 additions and 209 deletions
+119 -1
View File
@@ -1,10 +1,14 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use utoipa::{IntoParams, ToSchema};
use uuid::Uuid;
use super::cursor::{CursorListResponse, CursorQuery, PageCursor};
use super::display_helpers::{
category_for, format_file_size, icon_class_for, icon_special_class_for,
};
use super::grant_dto::{ResourceContentDto, ResourceTypeDto};
use crate::domain::services::authorization::ResourceKind;
/// DTO for favorites item, enriched with item metadata via SQL JOIN
/// so the frontend does not need N+1 requests to resolve names/sizes.
@@ -104,6 +108,120 @@ pub struct BatchFavoritesResult {
pub favorites: Vec<FavoriteItemDto>,
}
// ════════════════════════════════════════════════════════════════════════════
// Cursor-paginated favorites resources (GET /api/favorites/resources)
// ════════════════════════════════════════════════════════════════════════════
/// Raw row returned by the UNION ALL query that joins `auth.user_favorites`
/// with `storage.files` / `storage.folders`. Never serialised directly.
pub struct FavoriteResourceRow {
pub resource_type: String, // "file" | "folder"
pub resource_id: Uuid,
pub name: String,
pub parent_id: Option<Uuid>,
pub mime_type: Option<String>,
/// `-1` for folders, actual byte-count for files.
pub size: i64,
pub resource_created_at: DateTime<Utc>,
pub modified_at: DateTime<Utc>,
pub owner_id: Uuid,
/// `true` when `owner_id == requesting user_id`.
pub is_owner: bool,
pub favorited_at: DateTime<Utc>,
/// Human-readable path (e.g. `Documents/Work` for a folder,
/// `Documents/Work/report.pdf` for a file). Always populated; the
/// handler clears it to `""` when `is_owner` is false.
pub path: Option<String>,
// Pre-computed sort fields for cursor construction.
pub sort_str: Option<String>,
pub sort_int: Option<i64>,
pub sort_ts: Option<DateTime<Utc>>,
}
/// Opaque keyset-pagination cursor for `GET /api/favorites/resources`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FavoritesCursor {
/// Sort dimension active when this cursor was produced.
/// Values: `"name"` (default), `"type"`, `"favorited_at"`, `"modified_at"`,
/// `"size"`, `"owner"`.
#[serde(default = "FavoritesCursor::default_order")]
pub order_by: String,
/// UUID of the last item on the previous page (tie-breaker).
pub resource_id: Uuid,
/// `LOWER(name)` for `name`/`type` sorts; `LOWER(username)` for `owner`.
#[serde(skip_serializing_if = "Option::is_none")]
pub sort_str: Option<String>,
/// Multipurpose integer: `folder_first` for `name`, `type_order` for `type`,
/// size in bytes for `size`.
#[serde(skip_serializing_if = "Option::is_none")]
pub sort_int: Option<i64>,
/// Timestamp for `favorited_at` and `modified_at` sorts.
#[serde(skip_serializing_if = "Option::is_none")]
pub sort_ts: Option<DateTime<Utc>>,
/// Whether the result set was reversed — must match on every page.
#[serde(default)]
pub reverse: bool,
}
impl FavoritesCursor {
fn default_order() -> String {
"name".to_owned()
}
}
impl PageCursor for FavoritesCursor {}
/// Query parameters for `GET /api/favorites/resources`.
#[derive(Debug, Deserialize, IntoParams)]
pub struct FavoritesResourcesQuery {
/// Maximum items per page (1–200, default 50).
#[serde(default = "CursorQuery::default_limit")]
pub limit: u32,
/// Opaque cursor from a previous response. Omit to start from the first page.
pub cursor: Option<String>,
/// Sort / group-by dimension. Supported: `"name"` (default), `"type"`,
/// `"favorited_at"`, `"modified_at"`, `"size"`, `"owner"`.
pub order_by: Option<String>,
/// Comma-separated resource types to include, e.g. `"file,folder"`.
/// Omit to include both.
pub resource_types: Option<String>,
/// Reverse the sort order. Default `false`.
#[serde(default)]
pub reverse: bool,
}
impl FavoritesResourcesQuery {
pub fn limit_clamped(&self) -> usize {
self.limit.clamp(1, 200) as usize
}
pub fn decode_cursor(&self) -> Option<FavoritesCursor> {
self.cursor.as_deref().and_then(FavoritesCursor::decode)
}
/// Returns `None` when `resource_types` is absent (= include all).
pub fn resource_kinds(&self) -> Option<Vec<ResourceKind>> {
self.resource_types.as_deref().map(|s| {
s.split(',')
.filter_map(|t| ResourceKind::parse(t.trim()))
.collect()
})
}
}
/// One item in a `GET /api/favorites/resources` page.
#[derive(Debug, Serialize, ToSchema)]
pub struct FavoritesResourceItemDto {
pub resource_type: ResourceTypeDto,
/// When the resource was added to the user's favorites.
pub favorited_at: DateTime<Utc>,
/// Full resource details — shape determined by `resource_type`.
pub resource: ResourceContentDto,
}
/// Response envelope for `GET /api/favorites/resources`.
pub type FavoritesResourcesDto = CursorListResponse<FavoritesResourceItemDto>;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct BatchFavoritesStats {
/// How many items were requested
+17 -1
View File
@@ -2,8 +2,11 @@ use std::collections::HashSet;
use uuid::Uuid;
use crate::application::dtos::favorites_dto::{BatchFavoritesResult, FavoriteItemDto};
use crate::application::dtos::favorites_dto::{
BatchFavoritesResult, FavoriteItemDto, FavoriteResourceRow, FavoritesCursor,
};
use crate::common::errors::Result;
use crate::domain::services::authorization::ResourceKind;
/// Defines operations for managing user favorites
pub trait FavoritesUseCase: Send + Sync {
@@ -74,4 +77,17 @@ pub trait FavoritesRepositoryPort: Send + Sync + 'static {
user_id: Uuid,
item_ids: &[(&str, &str)], // (item_id, item_type) pairs
) -> Result<HashSet<String>>;
/// Cursor-paginated list of a user's favorited resources.
/// Items that no longer exist (deleted/trashed) are silently excluded.
/// `kinds = None` → both files and folders.
async fn list_resources_paged(
&self,
user_id: Uuid,
limit: usize,
cursor: Option<&FavoritesCursor>,
order_by: &str,
kinds: Option<&[ResourceKind]>,
reverse: bool,
) -> Result<Vec<FavoriteResourceRow>>;
}
+106 -1
View File
@@ -4,11 +4,14 @@ use std::sync::Arc;
use tracing::info;
use uuid::Uuid;
use crate::application::dtos::cursor::PageCursor;
use crate::application::dtos::favorites_dto::{
BatchFavoritesResult, BatchFavoritesStats, FavoriteItemDto,
BatchFavoritesResult, BatchFavoritesStats, FavoriteItemDto, FavoriteResourceRow,
FavoritesCursor,
};
use crate::application::ports::favorites_ports::{FavoritesRepositoryPort, FavoritesUseCase};
use crate::common::errors::{DomainError, ErrorKind, Result};
use crate::domain::services::authorization::ResourceKind;
use crate::infrastructure::repositories::pg::FavoritesPgRepository;
/// Implementation of the FavoritesUseCase for managing user favorites.
@@ -155,3 +158,105 @@ impl FavoritesUseCase for FavoritesService {
self.repo.batch_check_favorites(user_id, item_ids).await
}
}
impl FavoritesService {
/// Cursor-paginated list of the user's favorited resources.
///
/// No authz needed — favorites are strictly user-scoped; the repository
/// enforces `WHERE user_id = $1` so users can only see their own entries.
///
/// Returns `(rows, next_cursor_encoded)`.
pub async fn list_resources_paged(
&self,
user_id: Uuid,
limit: usize,
cursor: Option<FavoritesCursor>,
order_by: &str,
kinds: Option<&[ResourceKind]>,
reverse: bool,
) -> Result<(Vec<FavoriteResourceRow>, Option<String>)> {
// Fetch one extra row to detect whether a next page exists.
let mut rows = self
.repo
.list_resources_paged(
user_id,
limit + 1,
cursor.as_ref(),
order_by,
kinds,
reverse,
)
.await?;
let next_cursor = if rows.len() > limit {
let last = &rows[limit - 1];
let c = build_favorites_cursor(last, order_by, reverse);
rows.truncate(limit);
Some(c.encode())
} else {
None
};
Ok((rows, next_cursor))
}
}
/// Build the next-page cursor from the last row of the current page.
/// `reverse` is stored in the cursor so subsequent pages use the same direction.
fn build_favorites_cursor(
row: &FavoriteResourceRow,
order_by: &str,
reverse: bool,
) -> FavoritesCursor {
match order_by {
"type" => FavoritesCursor {
order_by: "type".to_owned(),
resource_id: row.resource_id,
sort_str: row.sort_str.clone(), // LOWER(name)
sort_int: row.sort_int, // type_order
sort_ts: None,
reverse,
},
"favorited_at" => FavoritesCursor {
order_by: "favorited_at".to_owned(),
resource_id: row.resource_id,
sort_str: None,
sort_int: None,
sort_ts: row.sort_ts, // favorited_at timestamp
reverse,
},
"modified_at" => FavoritesCursor {
order_by: "modified_at".to_owned(),
resource_id: row.resource_id,
sort_str: None,
sort_int: None,
sort_ts: row.sort_ts, // modified_at timestamp
reverse,
},
"size" => FavoritesCursor {
order_by: "size".to_owned(),
resource_id: row.resource_id,
sort_str: None,
sort_int: row.sort_int, // file size in bytes
sort_ts: None,
reverse,
},
"owner" => FavoritesCursor {
order_by: "owner".to_owned(),
resource_id: row.resource_id,
sort_str: row.sort_str.clone(), // LOWER(username)
sort_int: None,
sort_ts: row.sort_ts, // favorited_at (secondary sort)
reverse,
},
_ => FavoritesCursor {
// "name" (default): sort_str = LOWER(name), sort_int = folder_first (0 = folder, 1 = file)
order_by: "name".to_owned(),
resource_id: row.resource_id,
sort_str: row.sort_str.clone(),
sort_int: row.sort_int, // folder_first
sort_ts: None,
reverse,
},
}
}