Skip to content

feat(requests): add more sorting options#3184

Open
0xSysR3ll wants to merge 1 commit into
developfrom
0xsysr3ll/feat/add-requests-sorting-options
Open

feat(requests): add more sorting options#3184
0xSysR3ll wants to merge 1 commit into
developfrom
0xsysr3ll/feat/add-requests-sorting-options

Conversation

@0xSysR3ll

@0xSysR3ll 0xSysR3ll commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Description

This PR adds more sorting options to the requests page:

  • Popularity
  • Release / First Air Date
  • TMDB Rating
  • Title

The sorting logic has been added to a dedicated module server/lib/requestSort.ts instead of the actual request.ts to keep the route handler focused. This also keeps sorting unit tests separate from request route tests.

How Has This Been Tested?

Used the new filters.

Screenshots / Logs (if applicable)

Checklist:

  • I have read and followed the contribution guidelines.
  • Disclosed any use of AI (see our policy)
  • I have updated the documentation accordingly.
  • All new and existing tests passed.
  • Successful build pnpm build
  • Translation keys pnpm i18n:extract
  • Database migration (if required)

Summary by CodeRabbit

  • New Features
    • Expanded media request sorting to support popularity, releaseDate, voteAverage (TMDB rating), and title, alongside existing added and modified.
    • Updated the request list UI to let users choose these new sort options and sends the selected sort/sortDirection to the backend.
  • Tests
    • Added/expanded unit tests for sort parsing and TMDB-based sorting, including caching, ordering, and failure handling.
    • Added integration tests verifying request ordering for added/modified with explicit sort directions.

@0xSysR3ll 0xSysR3ll requested a review from a team as a code owner June 20, 2026 21:08
@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c33a9fc5-4241-4d33-873e-0be816e06836

📥 Commits

Reviewing files that changed from the base of the PR and between 3b966f0 and 7376266.

📒 Files selected for processing (8)
  • next-env.d.ts
  • seerr-api.yml
  • server/lib/requestSort.test.ts
  • server/lib/requestSort.ts
  • server/routes/request.test.ts
  • server/routes/request.ts
  • src/components/RequestList/index.tsx
  • src/i18n/locale/en.json
✅ Files skipped from review due to trivial changes (2)
  • next-env.d.ts
  • src/i18n/locale/en.json
🚧 Files skipped from review as they are similar to previous changes (5)
  • server/routes/request.test.ts
  • seerr-api.yml
  • server/routes/request.ts
  • src/components/RequestList/index.tsx
  • server/lib/requestSort.ts

📝 Walkthrough

Walkthrough

Adds six sort fields (added, modified, popularity, releaseDate, voteAverage, title) and a sortDirection parameter to the requests list. A new requestSort library handles parsing, TMDB attribute fetching with in-memory caching, and conditional DB vs. in-memory sorting. The frontend RequestList dropdown and API spec are updated accordingly.

Changes

Extended Request Sorting

Layer / File(s) Summary
requestSort types, parsing, and column mapping
server/lib/requestSort.ts
Defines RequestSortField, RequestSortDirection, ParsedRequestSort types; parseRequestSort for validating query params with defaults (added/desc); isTmdbRequestSort classifier; and getRequestSortColumn mapping fields to DB timestamp columns.
TMDB fetch-cache and in-memory sort
server/lib/requestSort.ts
Adds an in-memory TMDB attribute cache helper and sortRequestsByTmdbField, which deduplicates requests, concurrently fetches title/popularity/voteAverage/releaseDate, sorts with deterministic tie-breaking by request id, and handles missing cache entries.
requestSort unit tests
server/lib/requestSort.test.ts
Comprehensive unit tests for parseRequestSort defaults and unknown-value fallbacks, isTmdbRequestSort field classification, getRequestSortColumn DB column mappings, and sortRequestsByTmdbField behavior including fetch de-duplication, tie-breaking, and graceful TMDB failure handling.
Request route sort integration
server/routes/request.ts
Imports requestSort helpers, parses sort query params via parseRequestSort, and branches pagination: TMDB sorts use getMany + in-memory sortRequestsByTmdbField + array slicing; non-TMDB sorts use DB orderBy/addOrderBy + getManyAndCount.
Request route integration tests
server/routes/request.test.ts
Integration tests seeding two MediaRequest records and asserting id ordering for sort=added&sortDirection=asc and sort=modified&sortDirection=desc via GET /request.
RequestList UI sort expansion and i18n
src/components/RequestList/index.tsx, src/i18n/locale/en.json
Expands the Sort type union, adds localized English labels for the four new sort modes, extends the sort dropdown with those options, and removes superseded narrower type declarations.
API spec update and next-env path fix
seerr-api.yml, next-env.d.ts
Expands sort enum and adds sortDirection description in the OpenAPI spec for GET /request. Updates next-env.d.ts to reference the dev-specific route types path.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant RequestRoute as GET /request
  participant parseRequestSort
  participant DB as TypeORM Query
  participant sortRequestsByTmdbField
  participant TheMovieDb

  Client->>RequestRoute: GET /request?sort=popularity&sortDirection=asc
  RequestRoute->>parseRequestSort: sort="popularity", sortDirection="asc"
  parseRequestSort-->>RequestRoute: { field: "popularity", direction: "asc" }
  RequestRoute->>DB: query.getMany() (all matching records, no DB order)
  DB-->>RequestRoute: MediaRequest[]
  RequestRoute->>sortRequestsByTmdbField: requests[], "popularity", "asc"
  sortRequestsByTmdbField->>TheMovieDb: fetch popularity per unique tmdbId
  TheMovieDb-->>sortRequestsByTmdbField: cached attributes
  sortRequestsByTmdbField-->>RequestRoute: sorted MediaRequest[]
  RequestRoute->>RequestRoute: slice(skip, skip+pageSize)
  RequestRoute-->>Client: { results[], pageInfo }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • gauthier-th
  • fallenbagel
  • M0NsTeRRR

Poem

🐇 Hop hop, the request list grows anew,
Sorted by title, by rating, by debut!
Popularity, release date—take your pick,
TMDB fetched and cached real quick.
Ascending or descending, left or right,
This bunny sorted everything just right! ✨

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding more sorting options to the requests functionality.
Linked Issues check ✅ Passed The pull request implements all sorting options requested in issue #2070: request date, last modified date, popularity, release date, TMDB rating, and title with both ascending and descending directions.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the sorting functionality specified in issue #2070; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@0xSysR3ll 0xSysR3ll force-pushed the 0xsysr3ll/feat/add-requests-sorting-options branch from 3b966f0 to ef200eb Compare June 20, 2026 21:13

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
server/routes/request.ts (1)

174-183: ⚖️ Poor tradeoff

Consider adding pagination limits or response-time monitoring for TMDB sorts.

The TMDB sort path loads all matching requests into memory before sorting and slicing. For large request lists (thousands of records), this could cause:

  • Memory pressure from loading all records
  • Slow response times from concurrent TMDB API calls (even with deduplication)
  • Re-fetching TMDB data on every page navigation since the cache is per-request

This is an acceptable tradeoff given TMDB fields can't be sorted at the DB level, but consider adding observability (e.g., logging when request count exceeds a threshold) to monitor real-world impact.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/routes/request.ts` around lines 174 - 183, Add observability to the
TMDB sort path in the isTmdbRequestSort block to monitor real-world performance
impact. After loading all records with query.getMany() and before calling
sortRequestsByTmdbField, add logging that triggers when the request count
exceeds a reasonable threshold (e.g., 1000 records). This will help identify
cases where the in-memory sorting of large datasets is causing performance
issues without blocking the functionality.
server/lib/requestSort.ts (1)

57-64: ⚡ Quick win

Consider narrowing the type signature for semantic accuracy.

The function signature accepts all RequestSortField values, but according to the route context (server/routes/request.ts:186), this function is only called for non-TMDB fields (added and modified). Narrowing the parameter type to 'added' | 'modified' would make the contract clearer and catch incorrect usage at compile time.

♻️ Suggested type narrowing
-export function getRequestSortColumn(field: RequestSortField): string {
+export function getRequestSortColumn(field: 'added' | 'modified'): string {
   switch (field) {
+    case 'added':
+      return 'request.createdAt';
     case 'modified':
       return 'request.updatedAt';
-    default:
-      return 'request.createdAt';
   }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/lib/requestSort.ts` around lines 57 - 64, The getRequestSortColumn
function currently accepts the broad RequestSortField type parameter, but it is
only called with 'added' and 'modified' values according to the actual usage
context. Narrow the parameter type from RequestSortField to a union type that
only includes 'added' | 'modified' to make the function contract clearer and
prevent invalid calls from being compiled. Update the switch statement's default
case accordingly since those are now the only expected values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@next-env.d.ts`:
- Line 3: The import path in next-env.d.ts uses an incorrect and unstable path
by including `/dev` in the route. Remove `/dev` from the import statement so
that it reads `import "./.next/types/routes.d.ts";` instead of `import
"./.next/dev/types/routes.d.ts";`. This uses the official stable proxy file path
that Next.js maintains for proper compatibility across environments. Note that
since next-env.d.ts is auto-generated, Next.js may revert this change
automatically on the next run.

In `@server/lib/requestSort.ts`:
- Around line 103-180: The sortRequestsByTmdbField function has complex sorting
logic including media deduplication, concurrent TMDB fetching, cache handling,
and field-specific comparisons, but currently lacks unit test coverage. Create
comprehensive unit tests that verify: deduplication by type-tmdbId key (ensuring
TMDB data is fetched only once per unique media), missing cache entry handling
(items without TMDB data sort consistently by ID), each of the four sort fields
(title, popularity, voteAverage, releaseDate) sort correctly in both ascending
and descending directions, tie-breaking logic (equal values ordered
deterministically by request ID), and error resilience (TMDB fetch failures
handled gracefully). Mock the TheMovieDb class and fetchMediaSortCache function
to simulate various success and failure scenarios for testing.
- Around line 145-155: The sortRequestsByTmdbField function in
server/lib/requestSort.ts has complex logic for TMDB data fetching,
deduplication, error handling, and sorting but lacks any unit test coverage in
server/lib/requestSort.test.ts. Add comprehensive test cases covering: the
scenario where items without cached TMDB data are placed at the end,
deduplication by type-tmdbId key, sorting by each field (popularity,
voteAverage, releaseDate, title) in both ascending and descending directions,
tie-breaking behavior using request.id, and error handling when TMDB API calls
fail.

---

Nitpick comments:
In `@server/lib/requestSort.ts`:
- Around line 57-64: The getRequestSortColumn function currently accepts the
broad RequestSortField type parameter, but it is only called with 'added' and
'modified' values according to the actual usage context. Narrow the parameter
type from RequestSortField to a union type that only includes 'added' |
'modified' to make the function contract clearer and prevent invalid calls from
being compiled. Update the switch statement's default case accordingly since
those are now the only expected values.

In `@server/routes/request.ts`:
- Around line 174-183: Add observability to the TMDB sort path in the
isTmdbRequestSort block to monitor real-world performance impact. After loading
all records with query.getMany() and before calling sortRequestsByTmdbField, add
logging that triggers when the request count exceeds a reasonable threshold
(e.g., 1000 records). This will help identify cases where the in-memory sorting
of large datasets is causing performance issues without blocking the
functionality.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 47ecd7a8-02b6-41f9-8342-66a5d61cc793

📥 Commits

Reviewing files that changed from the base of the PR and between 0a1f703 and 3b966f0.

📒 Files selected for processing (8)
  • next-env.d.ts
  • seerr-api.yml
  • server/lib/requestSort.test.ts
  • server/lib/requestSort.ts
  • server/routes/request.test.ts
  • server/routes/request.ts
  • src/components/RequestList/index.tsx
  • src/i18n/locale/en.json

Comment thread next-env.d.ts
Comment thread server/lib/requestSort.ts
Comment thread server/lib/requestSort.ts
@0xSysR3ll 0xSysR3ll force-pushed the 0xsysr3ll/feat/add-requests-sorting-options branch from ef200eb to 7376266 Compare June 20, 2026 21:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

More sorting choices for the Requests section

1 participant