Skip to content

feat: GET /api/artists/{id}/segments (replaces /api/artist/segments)#443

Closed
arpitgupta1214 wants to merge 5 commits into
testfrom
feat/api-get-artists-segments
Closed

feat: GET /api/artists/{id}/segments (replaces /api/artist/segments)#443
arpitgupta1214 wants to merge 5 commits into
testfrom
feat/api-get-artists-segments

Conversation

@arpitgupta1214
Copy link
Copy Markdown
Collaborator

@arpitgupta1214 arpitgupta1214 commented Apr 15, 2026

Summary

Per , this PR introduces the nested per-artist list route for the segments surface and removes the legacy flat route outright (no alias window).

  • Adds GET /api/artists/{id}/segments at app/api/artists/[id]/segments/route.ts.
  • The artist account ID now comes from the path; the query schema only accepts page and limit (identical validation rules as before).
  • Handler uses validateAuthContext() for authentication, then reuses the existing segments pagination logic.
  • Relocates the handler, validator, getArtistSegments, and mapArtistSegments from lib/artist/ to lib/artists/segments/ for surface cohesion. Tests are co-located under lib/artists/segments/__tests__/.
  • Deletes the legacy app/api/artist/segments/route.ts and the old lib/artist/* files in the same PR.

Response envelope ({ status, segments, pagination }) is unchanged.

Consumer coordination

  • chat is the only known consumer; the matching chat migration will follow.
  • A parallel POST /api/artists/[id]/segments PR is in flight in feat/api-post-segments on a sibling branch; this PR owns only the GET export so the two can coexist in the same route file post-merge.
  • Matching docs PR to follow.

Test plan

  • pnpm test — all 1907 tests pass (13 in the new lib/artists/segments suites).
  • pnpm lint:check — 0 errors, no ESLint config changes.
  • pnpm format:check — clean.
  • Preview deploy smoke: GET /api/artists/{artistId}/segments returns the same envelope as the legacy route for an authenticated request.
  • Confirm legacy GET /api/artist/segments returns 404 on the preview.

Summary by cubic

Adds GET /api/artists/{id}/segments to list an artist’s segments and removes the legacy GET /api/artist/segments. The artist ID now comes from the path; the response envelope is unchanged.

  • New Features

    • New route at app/api/artists/[id]/segments/route.ts; handler reads the path id and validates path, auth, and query via validateGetArtistSegmentsRequest().
    • Query accepts only page and limit; validator renamed to validateGetSegmentsQuery() and ignores stray artist_account_id.
    • getArtistSegments now takes (artistId, { page, limit }); logic is co-located under lib/artists/segments/ with new tests.
    • Validator return types follow the Validated* convention: ValidatedGetSegmentsQuery, ValidatedGetArtistSegmentsRequest.
  • Migration

    • Update clients from GET /api/artist/segments to GET /api/artists/{id}/segments.
    • Remove artist_account_id from query. Pass the artist ID in the path.

Written for commit d88d4c1. Summary will update on new commits.

arpitgupta1214 and others added 2 commits April 15, 2026 04:41
…435) (#440)

* chore(lint): scope eslint rules by file type + residual code fixes

Splits eslint.config.js into three file-scoped rule blocks so strict JSDoc
requirements apply only where they belong:

- all `**/*.ts`: keeps import/first, prettier, member-ordering, and tightens
  `no-unused-vars` to `argsIgnorePattern: "^_"` (was `"^_$"` which only
  matched bare `_`)
- `app/api/**/*.ts`: retains the full jsdoc ruleset per CLAUDE.md's "all
  API routes require JSDoc" mandate
- test files (`**/*.test.ts`, `**/__tests__/**`): disables
  `no-explicit-any` and `jsdoc/require-jsdoc` — tests legitimately need
  loose typing and don't ship as docs

Residual code-level fixes the new config surfaces:
- `lib/credits/getCreditUsage.ts`: replace `(usage as any)` with a typed
  Partial record narrowing
- `lib/content/templates/types.ts`, `lib/trigger/fetchTriggerRuns.ts`:
  move `[key: string]: unknown` index signature before named fields
  (member-ordering)
- `lib/artists/createArtistInDb.ts`, `lib/workspaces/createWorkspaceInDb.ts`:
  drop unused `error` binding from catch
- misc test files: remove unused imports/vars, fix import/first ordering



* docs(api): meaningful JSDoc for 19 route handlers

Writes endpoint-specific JSDoc against the strict rules scoped to
`app/api/**`. Each handler now documents the HTTP verb + path, the
request body/query shape (referencing the `validate*Body` / `validate*Query`
schema file where applicable), the success response shape, and the
relevant non-200 status codes. No placeholder filler — every description
conveys something the signature does not.

Files:
- accounts/[id], admins/coding/pr, admins/coding/slack,
  admins/content/slack, admins/privy
- chats/[id]/messages/trailing
- coding-agent/callback, coding-agent/github
- connectors
- content (PATCH), content/analyze, content/caption, content/image,
  content/templates/[id], content/transcribe, content/upscale,
  content/video
- songs/analyze/presets
- transcribe



* fix(credits): use typed LanguageModelUsage fields; restore json() assertion in sandbox test

- `getCreditUsage`: drop the hand-rolled Partial-record cast and the v2-compat
  `promptTokens`/`completionTokens` fallback — `LanguageModelUsage` (= V3Usage)
  already types `inputTokens` / `outputTokens` directly, and the real runtime
  caller (`handleChatCredits`) passes this exact type. The compat branch was
  dead against the typed surface.
- `getCreditUsage.test.ts`: update mock usage objects from the legacy
  `promptTokens`/`completionTokens` shape to the SDK V3 shape the function is
  actually typed against.
- `postSandboxesFilesHandler.test.ts`: restore `result.json()` so the 500-path
  still asserts the response is valid JSON (not just status code), matching
  the original test intent.



* docs(api): correct @returns shape for coding-agent github webhook

Cubic review feedback: the JSDoc claimed `{ ok: true }` on 200 but the handler
returns `{ status: <outcome> }` payloads (`update_triggered`, `ignored`, `busy`,
`no_state`, `updating`) and `{ status: "error", error }` on non-200s. Update the
doc to match the actual contract.



---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
…nts)

Adds the nested list route for the segments surface migration:
- New route: app/api/artists/[id]/segments/route.ts (GET only)
- Handler reads artist id from the path, validates auth via
  validateAuthContext(), and reuses the existing pagination logic.
- Validator relocated to lib/artists/segments/validateGetSegmentsQuery.ts
  and no longer accepts artist_account_id as a query param.
- Relocates getArtistSegments / mapArtistSegments co-located logic under
  lib/artists/segments/ for surface cohesion.
- Removes the legacy app/api/artist/segments/route.ts and its old
  lib/artist/* files outright (no alias window).

Response envelope is unchanged.
@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Apr 15, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Apr 15, 2026 9:34pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 15, 2026

Warning

Rate limit exceeded

@arpitgupta1214 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 57 minutes and 14 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 57 minutes and 14 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cd5a2165-0632-4a85-880f-39f05f53cc5f

📥 Commits

Reviewing files that changed from the base of the PR and between ec0008b and d88d4c1.

⛔ Files ignored due to path filters (2)
  • lib/artists/segments/__tests__/getArtistSegmentsHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/artists/segments/__tests__/validateGetSegmentsQuery.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (7)
  • app/api/artists/[id]/segments/route.ts
  • lib/artist/getArtistSegmentsHandler.ts
  • lib/artists/segments/getArtistSegments.ts
  • lib/artists/segments/getArtistSegmentsHandler.ts
  • lib/artists/segments/mapArtistSegments.ts
  • lib/artists/segments/validateGetArtistSegmentsRequest.ts
  • lib/artists/segments/validateGetSegmentsQuery.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/api-get-artists-segments

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.

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 8 files

Confidence score: 4/5

  • This PR is likely safe to merge: the only reported concern is maintainability/style, not a functional bug or regression risk.
  • The most severe issue is in lib/artists/segments/__tests__/getArtistSegmentsHandler.test.ts, where the test suite exceeds the 100-line limit and should be split into smaller files or helpers to keep tests easier to read and maintain.
  • Given the issue is code-style focused (despite high confidence), merge risk stays low-to-moderate rather than blocking.
  • Pay close attention to lib/artists/segments/__tests__/getArtistSegmentsHandler.test.ts - oversized test file may reduce long-term readability and maintainability.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/artists/segments/__tests__/getArtistSegmentsHandler.test.ts">

<violation number="1" location="lib/artists/segments/__tests__/getArtistSegmentsHandler.test.ts:1">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

Split this test suite into smaller files or extracted helpers; it exceeds the 100-line file limit.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client as Consumer (Chat)
    participant Route as API Route ([id]/segments)
    participant Auth as validateAuthContext
    participant Val as Validators
    participant Lib as getArtistSegments
    participant DB as Supabase

    Note over Client,DB: NEW: Migrated Artist Segments Flow (Nested Route)

    Client->>Route: GET /api/artists/{id}/segments?page=1&limit=20
    
    Route->>Val: NEW: validateAccountParams(id)
    alt Invalid UUID
        Val-->>Route: 400 Bad Request
        Route-->>Client: 400 Error
    else Valid UUID
        Val-->>Route: validatedParams
    end

    Route->>Auth: NEW: validateAuthContext(request)
    alt Unauthorized / Invalid Session
        Auth-->>Route: 401/403 NextResponse
        Route-->>Client: Error Response
    else Valid Session
        Auth-->>Route: AuthContext
    end

    Route->>Val: CHANGED: validateGetSegmentsQuery(searchParams)
    Note right of Val: No longer expects artist_account_id in query
    alt Invalid page/limit
        Val-->>Route: 400 Bad Request
        Route-->>Client: 400 Error
    else Valid Query
        Val-->>Route: { page, limit }
    end

    Route->>Lib: getArtistSegments(artist_id, page, limit)
    
    Lib->>DB: selectArtistSegmentsCount(artist_id)
    DB-->>Lib: total_count
    
    Lib->>DB: selectArtistSegmentsWithDetails(artist_id, offset, limit)
    DB-->>Lib: raw_segments

    Lib->>Lib: mapArtistSegments(raw_segments)
    
    Lib-->>Route: { status: "success", segments, pagination }
    
    Route-->>Client: 200 OK + JSON Payload
Loading

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.

@@ -0,0 +1,167 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot Apr 15, 2026

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

Split this test suite into smaller files or extracted helpers; it exceeds the 100-line file limit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/artists/segments/__tests__/getArtistSegmentsHandler.test.ts, line 1:

<comment>Split this test suite into smaller files or extracted helpers; it exceeds the 100-line file limit.</comment>

<file context>
@@ -0,0 +1,167 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest, NextResponse } from "next/server";
+
</file context>
Fix with Cubic

…ntsQuery

The validator-inferred GetSegmentsQuery already has { page, limit }; adding a
second GetArtistSegmentsParams type just to graft artist_account_id on top
duplicated the shape. Take the artist id as a positional arg and accept the
validator output as-is.
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

0 issues found across 3 files (changes from recent commits).

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

…tistSegmentsRequest

Matches the project validate<Verb><Resource>Request pattern used by
validateDeleteArtistRequest / validateGetArtistsRequest — the handler no longer
calls validateAccountParams/validateAuthContext/validateGetSegmentsQuery
individually.
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

0 issues found across 2 files (changes from recent commits).

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

Matches project convention (ValidatedUpscaleBody, ValidatedGetTasksQuery,
etc.): GetSegmentsQuery -> ValidatedGetSegmentsQuery, GetArtistSegmentsRequest
-> ValidatedGetArtistSegmentsRequest.
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

0 issues found across 3 files (changes from recent commits).

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

@arpitgupta1214
Copy link
Copy Markdown
Collaborator Author

Smoke Test Results — GET /api/artists/{id}/segments

Tested against Vercel preview deployment.

# Test Expected Actual Result
1 Success (default pagination) 200 200
2 Success (?page=1&limit=5) 200, limit=5 200, limit=5
3 No auth (omit x-api-key) 401 401
4 Invalid UUID path param 400 400
5 Invalid pagination (?page=0) 400 400
6 Invalid pagination (?limit=500) 400 400

All 6 tests pass. Error messages are clear and consistent ("id must be a valid UUID", "Too small", "Too big").

Test artist (Kanye) has 0 segments so response shape was verified with empty segments: [] and pagination: { total_count: 0, page: 1, limit: 20, total_pages: 0 }.

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.

1 participant