Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions app/api/accounts/artists/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { POST } from "../route";

vi.mock("@/lib/accounts/addArtistToAccountHandler", () => ({
addArtistToAccountHandler: vi.fn(),
}));

const { addArtistToAccountHandler } = await import("@/lib/accounts/addArtistToAccountHandler");

const ARTIST_ID = "11111111-1111-4111-8111-111111111111";

function makeReq(body: Record<string, unknown>): NextRequest {
return new NextRequest("https://example.com/api/accounts/artists", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}

describe("POST /api/accounts/artists", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("delegates to addArtistToAccountHandler and returns its response", async () => {
const handlerResponse = NextResponse.json({ success: true }, { status: 200 });
vi.mocked(addArtistToAccountHandler).mockResolvedValue(handlerResponse);

const req = makeReq({ artistId: ARTIST_ID });
const res = await POST(req);

expect(addArtistToAccountHandler).toHaveBeenCalledWith(req);
expect(res).toBe(handlerResponse);
});
});
18 changes: 6 additions & 12 deletions app/api/accounts/artists/route.ts

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

SRP

  • actual: handler code written in route.ts
  • required: handler + validator functions to match other endpoint architecture.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c2e35716. Extracted the orchestration to match the connectors endpoint architecture:

  • route.ts → one-line delegate: return addArtistToAccountHandler(req)
  • addArtistToAccountHandler(request) → thin request handler
  • validateAddArtistRequest(request) → validator (body + auth + target-account resolution → {accountId, artistId} or error)
  • linkArtistToAccount({accountId, artistId}) → business/DB step

Behavior preserved (400 body-first → 401 → 403/404 → link). 60 accounts tests green; tsc + lint + prettier clean on touched files.

Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { safeParseJson } from "@/lib/networking/safeParseJson";
import { validateAddArtistBody, type AddArtistBody } from "@/lib/accounts/validateAddArtistBody";
import { addArtistToAccountHandler } from "@/lib/accounts/addArtistToAccountHandler";

/**
* POST /api/accounts/artists
*
* Add an artist to an account's list of associated artists.
* Add an artist to the authenticated account's list of associated artists.
* Requires authentication (x-api-key or Authorization bearer token); the
* target account is derived from the credential. An optional email override
* is allowed only when the caller has access to that account.
* If the artist is already associated with the account, returns success.
*
* @param req - The incoming request with email and artistId in body
* @param req - The incoming request with artistId (and optional email) in body
* @returns NextResponse with success status or error
*/
export async function POST(req: NextRequest) {
const body = await safeParseJson(req);

const validated = validateAddArtistBody(body);
if (validated instanceof NextResponse) {
return validated;
}

return addArtistToAccountHandler(validated as AddArtistBody);
return addArtistToAccountHandler(req);
}

/**
Expand Down
60 changes: 60 additions & 0 deletions lib/accounts/__tests__/addArtistToAccountHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { addArtistToAccountHandler } from "../addArtistToAccountHandler";

vi.mock("@/lib/accounts/validateAddArtistRequest", () => ({
validateAddArtistRequest: vi.fn(),
}));

vi.mock("@/lib/accounts/linkArtistToAccount", () => ({
linkArtistToAccount: vi.fn(),
}));

const { validateAddArtistRequest } = await import("@/lib/accounts/validateAddArtistRequest");
const { linkArtistToAccount } = await import("@/lib/accounts/linkArtistToAccount");

const ARTIST_ID = "11111111-1111-4111-8111-111111111111";
const ACCOUNT_ID = "22222222-2222-4222-8222-222222222222";

function makeReq(body: Record<string, unknown>): NextRequest {
return new NextRequest("https://example.com/api/accounts/artists", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}

describe("addArtistToAccountHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("returns the validation error and does not link when validation fails", async () => {
vi.mocked(validateAddArtistRequest).mockResolvedValue(
NextResponse.json({ status: "error" }, { status: 401 }),
);

const res = await addArtistToAccountHandler(makeReq({ artistId: ARTIST_ID }));

expect(res.status).toBe(401);
expect(linkArtistToAccount).not.toHaveBeenCalled();
});

it("links the resolved account and artist when validation passes", async () => {
vi.mocked(validateAddArtistRequest).mockResolvedValue({
accountId: ACCOUNT_ID,
artistId: ARTIST_ID,
});
vi.mocked(linkArtistToAccount).mockResolvedValue(
NextResponse.json({ success: true }, { status: 200 }),
);

const res = await addArtistToAccountHandler(makeReq({ artistId: ARTIST_ID }));

expect(res.status).toBe(200);
expect(linkArtistToAccount).toHaveBeenCalledWith({
accountId: ACCOUNT_ID,
artistId: ARTIST_ID,
});
});
});
63 changes: 63 additions & 0 deletions lib/accounts/__tests__/linkArtistToAccount.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { linkArtistToAccount } from "../linkArtistToAccount";

vi.mock("@/lib/supabase/account_artist_ids/getAccountArtistIds", () => ({
getAccountArtistIds: vi.fn(),
}));

vi.mock("@/lib/supabase/account_artist_ids/insertAccountArtistId", () => ({
insertAccountArtistId: vi.fn(),
}));

vi.mock("@/lib/networking/getCorsHeaders", () => ({
getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })),
}));

const { getAccountArtistIds } = await import(
"@/lib/supabase/account_artist_ids/getAccountArtistIds"
);
const { insertAccountArtistId } = await import(
"@/lib/supabase/account_artist_ids/insertAccountArtistId"
);

const ACCOUNT_ID = "22222222-2222-4222-8222-222222222222";
const ARTIST_ID = "11111111-1111-4111-8111-111111111111";

describe("linkArtistToAccount", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("inserts the artist and returns success when not already linked", async () => {
vi.mocked(getAccountArtistIds).mockResolvedValue([]);
vi.mocked(insertAccountArtistId).mockResolvedValue(undefined);

const res = await linkArtistToAccount({ accountId: ACCOUNT_ID, artistId: ARTIST_ID });

expect(res.status).toBe(200);
expect(insertAccountArtistId).toHaveBeenCalledWith(ACCOUNT_ID, ARTIST_ID);
});

it("returns success without inserting when the artist is already linked", async () => {
vi.mocked(getAccountArtistIds).mockResolvedValue([
{ artist_id: ARTIST_ID, account_id: ACCOUNT_ID },
] as never);

const res = await linkArtistToAccount({ accountId: ACCOUNT_ID, artistId: ARTIST_ID });

expect(res.status).toBe(200);
expect(insertAccountArtistId).not.toHaveBeenCalled();
});

it("returns 400 with a generic message (no raw error text) when the write fails", async () => {
vi.mocked(getAccountArtistIds).mockResolvedValue([]);
vi.mocked(insertAccountArtistId).mockRejectedValue(new Error("boom"));

const res = await linkArtistToAccount({ accountId: ACCOUNT_ID, artistId: ARTIST_ID });
const body = await res.json();

expect(res.status).toBe(400);
expect(body.message).toBe("Failed to add artist to account");
expect(JSON.stringify(body)).not.toContain("boom");
});
});
74 changes: 74 additions & 0 deletions lib/accounts/__tests__/resolveAddArtistAccountId.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextResponse } from "next/server";
import { resolveAddArtistAccountId } from "../resolveAddArtistAccountId";

vi.mock("@/lib/accounts/resolveAccountIdByEmail", () => ({
resolveAccountIdByEmail: vi.fn(),
}));

vi.mock("@/lib/auth/checkAccountAccess", () => ({
checkAccountAccess: vi.fn(),
}));

vi.mock("@/lib/networking/getCorsHeaders", () => ({
getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })),
}));

const { resolveAccountIdByEmail } = await import("@/lib/accounts/resolveAccountIdByEmail");
const { checkAccountAccess } = await import("@/lib/auth/checkAccountAccess");

const AUTH_ACCOUNT_ID = "22222222-2222-4222-8222-222222222222";
const TARGET_ACCOUNT_ID = "33333333-3333-4333-8333-333333333333";

describe("resolveAddArtistAccountId", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("returns the authenticated account when no email is provided", async () => {
const result = await resolveAddArtistAccountId(AUTH_ACCOUNT_ID, undefined);

expect(result).toBe(AUTH_ACCOUNT_ID);
expect(resolveAccountIdByEmail).not.toHaveBeenCalled();
expect(checkAccountAccess).not.toHaveBeenCalled();
});

it("returns the account when email resolves to the caller's own account", async () => {
vi.mocked(resolveAccountIdByEmail).mockResolvedValue(AUTH_ACCOUNT_ID);

const result = await resolveAddArtistAccountId(AUTH_ACCOUNT_ID, "me@example.com");

expect(result).toBe(AUTH_ACCOUNT_ID);
expect(checkAccountAccess).not.toHaveBeenCalled();
});

it("returns the target account when the caller has access", async () => {
vi.mocked(resolveAccountIdByEmail).mockResolvedValue(TARGET_ACCOUNT_ID);
vi.mocked(checkAccountAccess).mockResolvedValue({ hasAccess: true, entityType: "artist" });

const result = await resolveAddArtistAccountId(AUTH_ACCOUNT_ID, "other@example.com");

expect(result).toBe(TARGET_ACCOUNT_ID);
expect(checkAccountAccess).toHaveBeenCalledWith(AUTH_ACCOUNT_ID, TARGET_ACCOUNT_ID);
});

it("returns 403 when the caller lacks access to the target account", async () => {
vi.mocked(resolveAccountIdByEmail).mockResolvedValue(TARGET_ACCOUNT_ID);
vi.mocked(checkAccountAccess).mockResolvedValue({ hasAccess: false });

const result = await resolveAddArtistAccountId(AUTH_ACCOUNT_ID, "other@example.com");

expect(result).toBeInstanceOf(NextResponse);
expect((result as NextResponse).status).toBe(403);
});

it("propagates the error response when the email is not found", async () => {
const notFound = NextResponse.json({ status: "error" }, { status: 404 });
vi.mocked(resolveAccountIdByEmail).mockResolvedValue(notFound);

const result = await resolveAddArtistAccountId(AUTH_ACCOUNT_ID, "missing@example.com");

expect(result).toBe(notFound);
expect(checkAccountAccess).not.toHaveBeenCalled();
});
});
104 changes: 104 additions & 0 deletions lib/accounts/__tests__/validateAddArtistRequest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { validateAddArtistRequest } from "../validateAddArtistRequest";

vi.mock("@/lib/auth/validateAuthContext", () => ({
validateAuthContext: vi.fn(),
}));

vi.mock("@/lib/accounts/resolveAddArtistAccountId", () => ({
resolveAddArtistAccountId: vi.fn(),
}));

vi.mock("@/lib/networking/getCorsHeaders", () => ({
getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })),
}));

const { validateAuthContext } = await import("@/lib/auth/validateAuthContext");
const { resolveAddArtistAccountId } = await import("@/lib/accounts/resolveAddArtistAccountId");

const ARTIST_ID = "11111111-1111-4111-8111-111111111111";
const AUTH_ACCOUNT_ID = "22222222-2222-4222-8222-222222222222";
const TARGET_ACCOUNT_ID = "33333333-3333-4333-8333-333333333333";

function makeReq(body: Record<string, unknown>): NextRequest {
return new NextRequest("https://example.com/api/accounts/artists", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}

describe("validateAddArtistRequest", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("returns a 400 response when artistId is missing (before auth)", async () => {
const result = await validateAddArtistRequest(makeReq({}));

expect(result).toBeInstanceOf(NextResponse);
expect((result as NextResponse).status).toBe(400);
expect(validateAuthContext).not.toHaveBeenCalled();
});

it("returns the auth error when no credential is provided", async () => {
vi.mocked(validateAuthContext).mockResolvedValue(
NextResponse.json({ status: "error" }, { status: 401 }),
);

const result = await validateAddArtistRequest(makeReq({ artistId: ARTIST_ID }));

expect(result).toBeInstanceOf(NextResponse);
expect((result as NextResponse).status).toBe(401);
expect(resolveAddArtistAccountId).not.toHaveBeenCalled();
});

it("derives the account from the authenticated credential when no email is given", async () => {
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: AUTH_ACCOUNT_ID,
orgId: null,
authToken: "token",
});
vi.mocked(resolveAddArtistAccountId).mockResolvedValue(AUTH_ACCOUNT_ID);

const result = await validateAddArtistRequest(makeReq({ artistId: ARTIST_ID }));

expect(resolveAddArtistAccountId).toHaveBeenCalledWith(AUTH_ACCOUNT_ID, undefined);
expect(result).toEqual({ accountId: AUTH_ACCOUNT_ID, artistId: ARTIST_ID });
});

it("passes through the resolved target account when an email override is accepted", async () => {
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: AUTH_ACCOUNT_ID,
orgId: null,
authToken: "token",
});
vi.mocked(resolveAddArtistAccountId).mockResolvedValue(TARGET_ACCOUNT_ID);

const result = await validateAddArtistRequest(
makeReq({ artistId: ARTIST_ID, email: "other@example.com" }),
);

expect(resolveAddArtistAccountId).toHaveBeenCalledWith(AUTH_ACCOUNT_ID, "other@example.com");
expect(result).toEqual({ accountId: TARGET_ACCOUNT_ID, artistId: ARTIST_ID });
});

it("returns the resolver error when an email override is denied", async () => {
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: AUTH_ACCOUNT_ID,
orgId: null,
authToken: "token",
});
vi.mocked(resolveAddArtistAccountId).mockResolvedValue(
NextResponse.json({ status: "error" }, { status: 403 }),
);

const result = await validateAddArtistRequest(
makeReq({ artistId: ARTIST_ID, email: "other@example.com" }),
);

expect(result).toBeInstanceOf(NextResponse);
expect((result as NextResponse).status).toBe(403);
});
});
Loading
Loading