feat: GET /api/artists/{id}/segments (replaces /api/artist/segments)#443
feat: GET /api/artists/{id}/segments (replaces /api/artist/segments)#443arpitgupta1214 wants to merge 5 commits into
Conversation
…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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (7)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
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"; | |||
There was a problem hiding this comment.
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>
…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.
…tistSegmentsRequest Matches the project validate<Verb><Resource>Request pattern used by validateDeleteArtistRequest / validateGetArtistsRequest — the handler no longer calls validateAccountParams/validateAuthContext/validateGetSegmentsQuery individually.
Matches project convention (ValidatedUpscaleBody, ValidatedGetTasksQuery, etc.): GetSegmentsQuery -> ValidatedGetSegmentsQuery, GetArtistSegmentsRequest -> ValidatedGetArtistSegmentsRequest.
Smoke Test Results —
|
| # | 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 }.
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).
GET /api/artists/{id}/segmentsatapp/api/artists/[id]/segments/route.ts.pageandlimit(identical validation rules as before).validateAuthContext()for authentication, then reuses the existing segments pagination logic.getArtistSegments, andmapArtistSegmentsfromlib/artist/tolib/artists/segments/for surface cohesion. Tests are co-located underlib/artists/segments/__tests__/.app/api/artist/segments/route.tsand the oldlib/artist/*files in the same PR.Response envelope (
{ status, segments, pagination }) is unchanged.Consumer coordination
chatis the only known consumer; the matching chat migration will follow.POST /api/artists/[id]/segmentsPR is in flight infeat/api-post-segmentson a sibling branch; this PR owns only theGETexport so the two can coexist in the same route file post-merge.Test plan
pnpm test— all 1907 tests pass (13 in the newlib/artists/segmentssuites).pnpm lint:check— 0 errors, no ESLint config changes.pnpm format:check— clean.GET /api/artists/{artistId}/segmentsreturns the same envelope as the legacy route for an authenticated request.GET /api/artist/segmentsreturns 404 on the preview.Summary by cubic
Adds
GET /api/artists/{id}/segmentsto list an artist’s segments and removes the legacyGET /api/artist/segments. The artist ID now comes from the path; the response envelope is unchanged.New Features
app/api/artists/[id]/segments/route.ts; handler reads the pathidand validates path, auth, and query viavalidateGetArtistSegmentsRequest().pageandlimit; validator renamed tovalidateGetSegmentsQuery()and ignores strayartist_account_id.getArtistSegmentsnow takes(artistId, { page, limit }); logic is co-located underlib/artists/segments/with new tests.Validated*convention:ValidatedGetSegmentsQuery,ValidatedGetArtistSegmentsRequest.Migration
GET /api/artist/segmentstoGET /api/artists/{id}/segments.artist_account_idfrom query. Pass the artist ID in the path.Written for commit d88d4c1. Summary will update on new commits.