-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from 3 commits
422449c
b6a3bff
7da5c28
3d96e2b
ee3e32c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -39,3 +39,6 @@ yarn-error.log* | |
# typescript | ||
*.tsbuildinfo | ||
next-env.d.ts | ||
|
||
# vscode | ||
.vscode/ |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
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 = { | ||
numberOfItems: 3, | ||
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 | ||
}, | ||
}); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// 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 { | ||
numberOfItems: number | 0; | ||
unclaimedItems: | ||
| { | ||
id: number; | ||
name: string; | ||
quantity: number; | ||
expirationDate: Date | null; | ||
}[] | ||
| []; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: this is kinda wonky. why is this a union type with empty array? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was an error earlier because when I pulled it in the tests it would be null and not an empty array, but I'm not getting the error anymore so I've changed it back to normal. |
||
} | ||
|
||
/** | ||
* 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({ | ||
numberOfItems: unclaimedItems?.length, // ?.length for when unclaimedItems is undefined | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. no need to return the number of items There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done! |
||
unclaimedItems: unclaimedItems, | ||
} as UnclaimedItemsResponse); | ||
} |
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; | ||
} |
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; | ||
} |
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.
nit: this can just be 0
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.
Got it!
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.
!