Skip to content

Commit eba1a8d

Browse files
alexdcdckavinphan
authored andcommitted
refactor date param validation
1 parent b4e0886 commit eba1a8d

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

src/app/api/unclaimedItems/route.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ test("Should be successful when both expirationDateBefore, expirationDateAfter v
131131
});
132132
});
133133

134-
test("Should be successful when both expirationDateBefore valid, expirationDateAfter missing", async () => {
134+
test("Should be successful when expirationDateBefore valid, expirationDateAfter missing", async () => {
135135
await testApiHandler({
136136
appHandler,
137137
requestPatcher(request) {
@@ -160,7 +160,7 @@ test("Should be successful when both expirationDateBefore valid, expirationDateA
160160
});
161161
});
162162

163-
test("Should be successful when both expirationDateBefore missing, expirationDateAfter valid", async () => {
163+
test("Should be successful when expirationDateBefore missing, expirationDateAfter valid", async () => {
164164
await testApiHandler({
165165
appHandler,
166166
requestPatcher(request) {

src/app/api/unclaimedItems/route.ts

+15-8
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,17 @@ interface ItemsResponse {
2424
/**
2525
* Takes a date string, validates it, and parses it into a Date object.
2626
* @params dateString: the date string to parse
27-
* @returns the parsed date string or null if the date string is invalid
27+
* @returns undefined if the date string is undefined/null
28+
* @returns null if the date string is defined but invalid
29+
* @returns a Date object if the date string is valid
2830
*/
29-
function parseDate(dateString: string): Date | null {
31+
function parseDateIfDefined(
32+
dateString: string | null
33+
): Date | null | undefined {
3034
// see https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript
35+
if (!dateString) {
36+
return undefined;
37+
}
3138
const date = new Date(dateString);
3239
if (
3340
Object.prototype.toString.call(date) === "[object Date]" &&
@@ -56,12 +63,12 @@ export async function GET(request: NextRequest) {
5663
}
5764

5865
const params = request.nextUrl.searchParams;
59-
const expirationDateBefore = params.has("expirationDateBefore")
60-
? parseDate(params.get("expirationDateBefore") as string)
61-
: undefined;
62-
const expirationDateAfter = params.has("expirationDateAfter")
63-
? parseDate(params.get("expirationDateAfter") as string)
64-
: undefined;
66+
const expirationDateBefore = parseDateIfDefined(
67+
params.get("expirationDateBefore")
68+
);
69+
const expirationDateAfter = parseDateIfDefined(
70+
params.get("expirationDateAfter")
71+
);
6572

6673
if (expirationDateBefore === null) {
6774
return argumentError(

0 commit comments

Comments
 (0)