-
Notifications
You must be signed in to change notification settings - Fork 9
feat: POST /api/artists/{id}/segments (manual segment creation) #444
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b68d704
feat(api): add POST /api/artists/{id}/segments for manual segment cre…
arpitgupta1214 b31faf7
refactor(api): bundle POST segments validations into validatePostArti…
arpitgupta1214 806c6ce
refactor(api): prefix validator return types with Validated
arpitgupta1214 eeff513
fix(api): return 201 Created for POST /api/artists/{id}/segments
arpitgupta1214 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { postArtistSegmentsHandler } from "@/lib/artists/segments/postArtistSegmentsHandler"; | ||
|
|
||
| /** | ||
| * OPTIONS handler for CORS preflight requests. | ||
| * | ||
| * @returns A NextResponse with CORS headers. | ||
| */ | ||
| export async function OPTIONS() { | ||
| return new NextResponse(null, { | ||
| status: 200, | ||
| headers: getCorsHeaders(), | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * POST /api/artists/{id}/segments | ||
| * | ||
| * Manually creates segments for the specified artist by delegating to the shared | ||
| * `createSegments` handler (also exposed via the MCP `create_segments` tool). | ||
| * | ||
| * @param request - The incoming request object | ||
| * @param options - Route options containing params | ||
| * @param options.params - Route params containing the artist account ID | ||
| * @returns A NextResponse with the segment creation envelope | ||
| */ | ||
| export async function POST(request: NextRequest, options: { params: Promise<{ id: string }> }) { | ||
| return postArtistSegmentsHandler(request, options.params); | ||
| } |
245 changes: 245 additions & 0 deletions
245
lib/artists/segments/__tests__/postArtistSegmentsHandler.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,245 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { postArtistSegmentsHandler } from "../postArtistSegmentsHandler"; | ||
|
|
||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ | ||
| getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), | ||
| })); | ||
|
|
||
| const mockValidateAuthContext = vi.fn(); | ||
| vi.mock("@/lib/auth/validateAuthContext", () => ({ | ||
| validateAuthContext: (...args: unknown[]) => mockValidateAuthContext(...args), | ||
| })); | ||
|
|
||
| const mockSelectAccounts = vi.fn(); | ||
| vi.mock("@/lib/supabase/accounts/selectAccounts", () => ({ | ||
| selectAccounts: (...args: unknown[]) => mockSelectAccounts(...args), | ||
| })); | ||
|
|
||
| const mockCheckAccountArtistAccess = vi.fn(); | ||
| vi.mock("@/lib/artists/checkAccountArtistAccess", () => ({ | ||
| checkAccountArtistAccess: (...args: unknown[]) => mockCheckAccountArtistAccess(...args), | ||
| })); | ||
|
|
||
| const mockCreateSegments = vi.fn(); | ||
| vi.mock("@/lib/segments/createSegments", () => ({ | ||
| createSegments: (...args: unknown[]) => mockCreateSegments(...args), | ||
| })); | ||
|
|
||
| const ARTIST_ID = "550e8400-e29b-41d4-a716-446655440000"; | ||
| const REQUESTER_ACCOUNT_ID = "660e8400-e29b-41d4-a716-446655440000"; | ||
|
|
||
| function createRequest(body: unknown, headers: Record<string, string> = {}): NextRequest { | ||
| const defaultHeaders: Record<string, string> = { | ||
| "Content-Type": "application/json", | ||
| "x-api-key": "test-api-key", | ||
| }; | ||
| return new NextRequest(`http://localhost/api/artists/${ARTIST_ID}/segments`, { | ||
| method: "POST", | ||
| headers: { ...defaultHeaders, ...headers }, | ||
| body: JSON.stringify(body), | ||
| }); | ||
| } | ||
|
|
||
| describe("postArtistSegmentsHandler", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mockValidateAuthContext.mockResolvedValue({ | ||
| accountId: REQUESTER_ACCOUNT_ID, | ||
| orgId: null, | ||
| authToken: "test-api-key", | ||
| }); | ||
| mockSelectAccounts.mockResolvedValue([{ id: ARTIST_ID, name: "Test Artist" }]); | ||
| mockCheckAccountArtistAccess.mockResolvedValue(true); | ||
| }); | ||
|
|
||
| it("returns 200 with success envelope when segments are created", async () => { | ||
| mockCreateSegments.mockResolvedValue({ | ||
| success: true, | ||
| status: "success", | ||
| message: "Successfully created 5 segments for artist", | ||
| data: { | ||
| supabase_segments: [], | ||
| supabase_artist_segments: [], | ||
| supabase_fan_segments: [], | ||
| segments: [], | ||
| }, | ||
| count: 5, | ||
| }); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(201); | ||
| expect(body).toEqual({ | ||
| status: "success", | ||
| segments_created: 5, | ||
| message: "Segments generated successfully.", | ||
| }); | ||
| expect(mockCreateSegments).toHaveBeenCalledWith({ | ||
| artist_account_id: ARTIST_ID, | ||
| prompt: "Segment my fans", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 400 when prompt is missing", async () => { | ||
| const request = createRequest({}); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| expect(body.status).toBe("error"); | ||
| expect(body.error).toBe("prompt is required"); | ||
| expect(mockCreateSegments).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 400 when prompt is empty", async () => { | ||
| const request = createRequest({ prompt: "" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| expect(body.error).toBe("prompt cannot be empty"); | ||
| expect(mockCreateSegments).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 400 when path id is not a valid UUID", async () => { | ||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler( | ||
| request, | ||
| Promise.resolve({ id: "not-a-uuid" }), | ||
| ); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| expect(body.status).toBe("error"); | ||
| expect(mockCreateSegments).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 401 when auth context fails", async () => { | ||
| mockValidateAuthContext.mockResolvedValue( | ||
| NextResponse.json( | ||
| { status: "error", error: "Exactly one of x-api-key or Authorization must be provided" }, | ||
| { status: 401 }, | ||
| ), | ||
| ); | ||
|
|
||
| const request = new NextRequest(`http://localhost/api/artists/${ARTIST_ID}/segments`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ prompt: "Segment my fans" }), | ||
| }); | ||
|
|
||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(401); | ||
| expect(body.error).toBe("Exactly one of x-api-key or Authorization must be provided"); | ||
| expect(mockCreateSegments).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 403 when caller lacks access to artist", async () => { | ||
| mockCheckAccountArtistAccess.mockResolvedValue(false); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(403); | ||
| expect(body.status).toBe("error"); | ||
| expect(body.error).toBe("Unauthorized segment creation attempt"); | ||
| expect(mockCreateSegments).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 404 when artist does not exist", async () => { | ||
| mockSelectAccounts.mockResolvedValue([]); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(404); | ||
| expect(body.error).toBe("Artist not found"); | ||
| expect(mockCheckAccountArtistAccess).not.toHaveBeenCalled(); | ||
| expect(mockCreateSegments).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 409 when createSegments reports no social account with feedback", async () => { | ||
| const feedback = "No Instagram accounts found for Test Artist. Follow these steps..."; | ||
| mockCreateSegments.mockResolvedValue({ | ||
| success: false, | ||
| status: "error", | ||
| message: "No social account found for this artist", | ||
| data: [], | ||
| count: 0, | ||
| feedback, | ||
| }); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(409); | ||
| expect(body).toEqual({ | ||
| status: "error", | ||
| error: "No social account found for this artist", | ||
| feedback, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 409 when createSegments reports no fans with feedback", async () => { | ||
| const feedback = "No social_fans records found for Test Artist. Follow these steps..."; | ||
| mockCreateSegments.mockResolvedValue({ | ||
| success: false, | ||
| status: "error", | ||
| message: "No fans found for this artist", | ||
| data: [], | ||
| count: 0, | ||
| feedback, | ||
| }); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(409); | ||
| expect(body).toEqual({ | ||
| status: "error", | ||
| error: "No fans found for this artist", | ||
| feedback, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 500 when createSegments reports a generic failure", async () => { | ||
| mockCreateSegments.mockResolvedValue({ | ||
| success: false, | ||
| status: "error", | ||
| message: "Failed to generate segment names", | ||
| data: [], | ||
| count: 0, | ||
| }); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(500); | ||
| expect(body).toEqual({ | ||
| status: "error", | ||
| error: "Failed to generate segment names", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 500 when createSegments throws", async () => { | ||
| mockCreateSegments.mockRejectedValue(new Error("Database exploded")); | ||
|
|
||
| const request = createRequest({ prompt: "Segment my fans" }); | ||
| const response = await postArtistSegmentsHandler(request, Promise.resolve({ id: ARTIST_ID })); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(500); | ||
| expect(body.error).toBe("Database exploded"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { createSegments } from "@/lib/segments/createSegments"; | ||
| import { validatePostArtistSegmentsRequest } from "@/lib/artists/segments/validatePostArtistSegmentsRequest"; | ||
|
|
||
| const NO_RESOURCE_ERROR_MESSAGES = new Set([ | ||
| "No social account found for this artist", | ||
| "No fans found for this artist", | ||
| ]); | ||
|
|
||
| /** | ||
| * Handler for POST /api/artists/{id}/segments. | ||
| * | ||
| * Validates the request then delegates to the shared `createSegments` handler | ||
| * that also powers the MCP `create_segments` tool. | ||
| * | ||
| * @param request - The incoming request object. | ||
| * @param params - The route params containing the artist account ID. | ||
| * @returns A NextResponse with the segment generation result envelope. | ||
| */ | ||
| export async function postArtistSegmentsHandler( | ||
| request: NextRequest, | ||
| params: Promise<{ id: string }>, | ||
| ): Promise<NextResponse> { | ||
| try { | ||
| const { id } = await params; | ||
|
|
||
| const validated = await validatePostArtistSegmentsRequest(request, id); | ||
| if (validated instanceof NextResponse) { | ||
| return validated; | ||
| } | ||
|
|
||
| const result = await createSegments({ | ||
| artist_account_id: validated.artistId, | ||
| prompt: validated.body.prompt, | ||
| }); | ||
|
|
||
| if (result.success) { | ||
| return NextResponse.json( | ||
| { | ||
| status: "success", | ||
| segments_created: result.count, | ||
| message: "Segments generated successfully.", | ||
| }, | ||
| { | ||
| status: 201, | ||
| headers: getCorsHeaders(), | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| const message = result.message ?? "Failed to create segments"; | ||
| const feedback = "feedback" in result ? result.feedback : undefined; | ||
| const isNoResourceError = NO_RESOURCE_ERROR_MESSAGES.has(message); | ||
| const statusCode = isNoResourceError ? 409 : 500; | ||
|
|
||
| return NextResponse.json( | ||
| { | ||
| status: "error", | ||
| error: message, | ||
| ...(feedback ? { feedback } : {}), | ||
| }, | ||
| { | ||
| status: statusCode, | ||
| headers: getCorsHeaders(), | ||
| }, | ||
| ); | ||
| } catch (error) { | ||
| console.error("[ERROR] postArtistSegmentsHandler:", error); | ||
| return NextResponse.json( | ||
| { | ||
| status: "error", | ||
| error: error instanceof Error ? error.message : "Internal server error", | ||
| }, | ||
| { | ||
| status: 500, | ||
| headers: getCorsHeaders(), | ||
| }, | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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
At 128 lines this handler is well over the 100-line limit and more than double every other handler in
lib/artists/(~50 lines each). Extract thecreateSegmentsresult-to-response mapping (lines 84–114, including theNO_RESOURCE_ERROR_MESSAGESset) into a small helper (e.g.,mapCreateSegmentsResult) to bring the file under the limit and keep a single level of responsibility.Prompt for AI agents