Skip to content

Commit b0cd893

Browse files
committed
use db, removed error logs, reformatted
1 parent 2170960 commit b0cd893

File tree

2 files changed

+20
-82
lines changed

2 files changed

+20
-82
lines changed

src/app/api/partnerDetails/[userId]/route.test.ts

+2-41
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,13 @@
11
import { testApiHandler } from "next-test-api-route-handler";
22
import { authMock } from "@/test/authMock";
33
import { dbMock } from "@/test/dbMock";
4-
import { expect, test, describe, jest } from "@jest/globals";
4+
import { expect, test, describe } from "@jest/globals";
55
import { OrganizationType } from "@prisma/client";
6-
7-
// mock @prisma/client so that new PrismaClient() -> dbMock for testing purposes
8-
jest.mock("@prisma/client", () => {
9-
return {
10-
PrismaClient: jest.fn().mockImplementation(() => dbMock),
11-
};
12-
});
13-
14-
// now that @prisma/client is mocked, we can the route code
156
import * as appHandler from "./route";
167

178
describe("POST /api/partnerDetails/[userId]", () => {
189
beforeEach(() => {
19-
jest.resetAllMocks();
10+
2011
});
2112

2213
//No Valid Session (401)
@@ -97,36 +88,6 @@ describe("POST /api/partnerDetails/[userId]", () => {
9788
});
9889
});
9990

100-
//Invalid User ID (400)
101-
test("returns 404 when no PartnerDetails record exists", async () => {
102-
authMock.mockReturnValueOnce({
103-
user: { id: "1", type: "SUPER_ADMIN" },
104-
expires: "",
105-
});
106-
107-
// DB returns null
108-
dbMock.partnerDetails.findUnique.mockResolvedValueOnce(null);
109-
110-
const formData = new FormData();
111-
formData.append("numberOfPatients", "8");
112-
formData.append("organizationType", "NON_PROFIT");
113-
114-
await testApiHandler({
115-
appHandler,
116-
params: { userId: "1" },
117-
async test({ fetch }) {
118-
const res = await fetch({
119-
method: "POST",
120-
body: formData,
121-
});
122-
123-
expect(res.status).toBe(404);
124-
const json = await res.json();
125-
expect(json).toEqual({ message: "Partner details not found" });
126-
},
127-
});
128-
});
129-
13091
//Valid Request (200)
13192
test("updates PartnerDetails and returns 200 for a valid request", async () => {
13293
authMock.mockReturnValueOnce({
+18-41
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
import { authenticationError, notFoundError, authorizationError, argumentError } from "@/util/responses";
1+
import { authenticationError, authorizationError, argumentError } from "@/util/responses";
22
import { auth } from "@/auth";
33
import { NextResponse, NextRequest } from "next/server";
44
import { z } from "zod";
5-
import { zfd } from "zod-form-data"; // <-- Added import from zod-form-data
6-
import { PrismaClient } from "@prisma/client";
7-
8-
// new Prisma Client
9-
const prisma = new PrismaClient();
5+
import { zfd } from "zod-form-data";
6+
import { db } from "@/db";
107

118
// Zod schema
129
const PartnerDetailsFormSchema = zfd.formData({
@@ -16,68 +13,52 @@ const PartnerDetailsFormSchema = zfd.formData({
1613

1714
/**
1815
* Updates a user's partner details.
19-
* Accepts parameters as FormData.
20-
*
21-
* @param {NextRequest} req The incoming request object.
22-
* @param {Object} context The route parameters containing the user ID.
23-
*
24-
* @returns {NextResponse} 401 if request is not authenticated.
25-
* @returns {NextResponse} 403 if the session user is a PARTNER modifying another user's details.
26-
* @returns {NextResponse} 400 if the request body is invalid.
27-
* @returns {NextResponse} 404 if no PartnerDetails record is found.
28-
* @returns {NextResponse} 200 with the updated partner details.
16+
* Parameters are passed as form data.
17+
*
18+
* @param numberOfPatients The number of patients associated with the partner
19+
* @param organizationType The type of the organization (NON_PROFIT, FOR_PROFIT, RELIGIOUS)
20+
* @param userId The ID of the user whose partner details are being updated
21+
*
22+
* @returns 401 if the request is not authenticated
23+
* @returns 403 if a PARTNER user attempts to modify another user's details
24+
* @returns 404 if no PartnerDetails record is found
25+
* @returns 200 with the updated partner details
2926
*/
3027
export async function POST(
3128
req: NextRequest,
3229
{ params }: { params: Promise<{ userId: string }> }
3330
) {
34-
try {
31+
3532
// authenticate the user session
3633
const session = await auth();
37-
if (!session || !session.user) {
34+
if (!session?.user) {
3835
return authenticationError("Session required");
3936
}
4037
const { user } = session;
4138

4239
// await params and ensure params.userId exists
4340
const { userId } = await params;
4441
if (!userId) {
45-
console.error("Missing user ID parameter in request");
4642
return argumentError("Missing user ID parameter");
4743
}
4844

49-
const userIdNumber = parseInt(userId, 10);
50-
if (isNaN(userIdNumber)) {
51-
console.error("Invalid user ID parameter");
52-
return argumentError("Invalid user ID");
53-
}
54-
5545
// partner users can only modify their own details
56-
if (user.type === "PARTNER" && String(user.id) !== String(userIdNumber)) {
46+
if (user.type === "PARTNER" && user.id !== userId) {
5747
return authorizationError("You are not allowed to modify this record");
5848
}
5949

6050
// parse FormData
6151
const formData = await req.formData();
6252
const parsedData = PartnerDetailsFormSchema.safeParse(formData);
6353
if (!parsedData.success) {
64-
console.error("Invalid form data:", parsedData.error);
6554
return argumentError("Invalid form data");
6655
}
6756

6857
const { numberOfPatients, organizationType } = parsedData.data;
6958

70-
// check if partnerDetails exists
71-
const partnerDetails = await prisma.partnerDetails.findUnique({
72-
where: { userId: userIdNumber },
73-
});
74-
if (!partnerDetails) {
75-
console.error("Partner details not found for user ID:", userIdNumber);
76-
return notFoundError("Partner details not found");
77-
}
78-
7959
// update PartnerDetails record
80-
const updatedPartnerDetails = await prisma.partnerDetails.update({
60+
const userIdNumber = Number(userId); //db schema accepts a number
61+
const updatedPartnerDetails = await db.partnerDetails.update({
8162
where: { userId: userIdNumber },
8263
data: {
8364
numberOfPatients,
@@ -86,8 +67,4 @@ export async function POST(
8667
});
8768

8869
return NextResponse.json(updatedPartnerDetails, { status: 200 });
89-
} catch (error) {
90-
console.error("Error updating PartnerDetails:", error);
91-
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
92-
}
9370
}

0 commit comments

Comments
 (0)