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
43 changes: 43 additions & 0 deletions src/app/api/testimonials/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, expect, it, vi, beforeEach } from "vitest";

vi.mock("@/lib/auth/get-user", () => ({
getAuthContext: vi.fn(),
}));

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

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

import { POST } from "./route";
import { getAuthContext } from "@/lib/auth/get-user";
import { createServiceClient } from "@/lib/supabase/service";

function postReq(json: () => Promise<unknown>) {
return {
url: "http://localhost/api/testimonials",
headers: new Headers(),
json,
} as any;
}

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

it("returns 400 for malformed JSON before creating a testimonial", async () => {
(getAuthContext as any).mockResolvedValue({
user: { id: "11111111-1111-4111-8111-111111111111" },
supabase: {},
});

const res = await POST(postReq(() => Promise.reject(new SyntaxError("bad json"))));

expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toBe("Invalid JSON body");
expect(createServiceClient).not.toHaveBeenCalled();
});
});
7 changes: 6 additions & 1 deletion src/app/api/testimonials/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,12 @@ export async function POST(request: NextRequest) {
}
const { user, supabase } = auth;

const body = await request.json();
let body: any;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
Comment on lines +74 to +78

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 The bare catch swallows every exception thrown by request.json(), not only SyntaxError. In nearly all real cases request.json() only throws SyntaxError, but if a stream or body-reader error surfaces here it will be reported to the caller as 400 Invalid JSON body rather than bubbling to the outer catch and returning a 500. Narrowing to SyntaxError keeps the semantics accurate and lets unexpected errors reach the generic handler.

Suggested change
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
try {
body = await request.json();
} catch (err) {
if (err instanceof SyntaxError) {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
throw err;
}

const { profile_id, gig_id, rating, content } = body;

// Must provide exactly one target
Expand Down
Loading