Skip to content
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

Davidgu/list unclaimed items query #12

Merged
merged 5 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

# vscode
.vscode/
37 changes: 34 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"react-dom": "^19.0.0",
"react-hot-toast": "^2.4.1",
"react-icons": "^5.4.0",
"uuid": "^11.0.5",
"zod": "^3.24.1",
"zod-form-data": "^2.0.5"
},
Expand All @@ -47,6 +48,7 @@
"next-test-api-route-handler": "^4.0.14",
"open-html": "^1.0.1",
"postcss": "^8",
"prettier": "^3.4.2",
"prisma": "^6.2.1",
"tailwindcss": "^3.4.1",
"ts-jest": "^29.2.5",
Expand Down
53 changes: 53 additions & 0 deletions src/app/api/unclaimedItems/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { testApiHandler } from "next-test-api-route-handler";
import * as appHandler from "./route";
import { expect, test } from "@jest/globals";
// import { authMock } from "@/test/authMock";
import { validateSession, invalidateSession } from "@/test/util/authMockUtils";
import { fillDbMockWithManyUnclaimedItems } from "@/test/util/dbMockUtils";
import { dbMock } from "@/test/dbMock";

test("Should return 401 for invalid session", async () => {
await testApiHandler({
appHandler,
async test({ fetch }) {
invalidateSession();

const res = await fetch({ method: "GET" });
await expect(res.status).toBe(401);
const json = await res.json();
await expect(json).toEqual({ message: "Session required" });
},
});
});

test("Should return 200 for valid session", async () => {
await testApiHandler({
appHandler,
async test({ fetch }) {
validateSession("ADMIN");

const res = await fetch({ method: "GET" });
await expect(res.status).toBe(200);
},
});
});

test("Should give correct database queries", async () => {
await testApiHandler({
appHandler,
async test({ fetch }) {
await fillDbMockWithManyUnclaimedItems(3);
validateSession("ADMIN");

const res = await fetch({ method: "GET" });
await expect(res.status).toBe(200);

// Check that the response json was written correctly
const expectedRet = {
unclaimedItems: await dbMock.unclaimedItem.findMany(),
};
const json = await res.json();
await expect(json).toEqual(JSON.parse(JSON.stringify(expectedRet))); // Needed to stringify and parse because the expiration field would cause an error because Date != ISOstring
},
});
});
37 changes: 37 additions & 0 deletions src/app/api/unclaimedItems/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// import { NextRequest } from 'next/server';
import { auth } from "@/auth";
import { authenticationError } from "@/util/responses";
import { db } from "@/db";
import { NextResponse } from "next/server";

// Response for GET /api/unclaimedItems
interface UnclaimedItemsResponse {
unclaimedItems: {
id: number;
name: string;
quantity: number;
expirationDate: Date | null;
}[];
}

/**
* Handles GET requests to retrieve unclaimed items from the unclaimedItem database.
* @returns 401 if the session is invalid
* @returns 500 if an unknown error occurs
* @returns 200 and a json response with the unclaimed items
*/
export async function GET() {
const session = await auth();
if (!session) return authenticationError("Session required");

if (!session?.user) {
return authenticationError("User not found");
}

// Get all unclaimed items
const unclaimedItems = await db.unclaimedItem.findMany();

return NextResponse.json({
unclaimedItems: unclaimedItems,
} as UnclaimedItemsResponse);
}
33 changes: 33 additions & 0 deletions src/test/util/authMockUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { authMock } from "@/test/authMock";
import { UserType } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";

// Helper util methods for testing

/**
* Helper method for invalidating a session
*/
export async function invalidateSession() {
authMock.mockReturnValueOnce(null);
}

/**
* Helper method for validating a session
* @param user Optional, default is { id: "1234", type: "ADMIN" }
* @param expires Optional, default is a day from now
* @returns A session object with the user and expires fields
*/
export async function validateSession(
userType: UserType,
expires: Date = new Date(Date.now() + 86400000)
) {
const createdSession = {
user: {
id: uuidv4(),
type: userType,
},
expires: expires.toISOString(),
};
authMock.mockReturnValueOnce(createdSession);
return createdSession;
}
36 changes: 36 additions & 0 deletions src/test/util/dbMockUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { dbMock } from "@/test/dbMock";
import { UnclaimedItem } from "@prisma/client";

// Helper util methods for testing

/**
* Helper method for creating unclaimed items
* Defines the db.unclaimedItem.findMany mock
* @param num Number of items to create
* @returns Array of UnclaimedItems returned by db.unclaimedItem.findMany mock
*/
export async function fillDbMockWithManyUnclaimedItems(
num: number
): Promise<UnclaimedItem[]> {
const items: UnclaimedItem[] = [];
const generatedIds = new Set<number>();

for (let i = 0; i < num; i++) {
let id: number;
do {
id = Math.floor(Math.random() * 1000000); // Generate a random integer ID
} while (generatedIds.has(id)); // Ensure the ID is unique

generatedIds.add(id);

items.push({
id: id,
name: `Test Item ${id}`,
quantity: Math.floor(Math.random() * 1000),
expirationDate: new Date(Date.now() + Math.floor(Math.random() * 10000)),
});
}

dbMock.unclaimedItem.findMany.mockResolvedValue(items);
return items;
}