Skip to content

Commit 478eee2

Browse files
committed
fix(validation): enforce year >= 2008 with consistent error message in Zod schema
1 parent ebe8a16 commit 478eee2

2 files changed

Lines changed: 11 additions & 14 deletions

File tree

app/api/streak/route.test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -260,23 +260,23 @@ describe('GET /api/streak', () => {
260260
const body = await response.json();
261261

262262
expect(response.status).toBe(400);
263-
expect(body.details.fieldErrors.year[0]).toContain('Invalid "year" parameter');
263+
expect(body.details.fieldErrors.year[0]).toContain('GitHub was founded in 2008');
264264
});
265265

266266
it('returns 400 for malformed numeric year', async () => {
267267
const response = await GET(makeRequest({ user: 'octocat', year: '100000' }));
268268
const body = await response.json();
269269

270270
expect(response.status).toBe(400);
271-
expect(body.details.fieldErrors.year[0]).toContain('Invalid "year" parameter');
271+
expect(body.details.fieldErrors.year[0]).toContain('GitHub was founded in 2008');
272272
});
273273

274274
it('returns 400 for years before GitHub existed', async () => {
275275
const response = await GET(makeRequest({ user: 'octocat', year: '1999' }));
276276
const body = await response.json();
277277

278278
expect(response.status).toBe(400);
279-
expect(body.details.fieldErrors.year[0]).toContain('Invalid "year" parameter');
279+
expect(body.details.fieldErrors.year[0]).toContain('GitHub was founded in 2008');
280280
});
281281

282282
it('returns 400 for future years', async () => {
@@ -286,7 +286,7 @@ describe('GET /api/streak', () => {
286286
const body = await response.json();
287287

288288
expect(response.status).toBe(400);
289-
expect(body.details.fieldErrors.year[0]).toContain('Invalid "year" parameter');
289+
expect(body.details.fieldErrors.year[0]).toContain('GitHub was founded in 2008');
290290
});
291291
});
292292

lib/validations.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,21 +34,18 @@ export const streakParamsSchema = z.object({
3434
font: z.string().optional(),
3535
year: z
3636
.string()
37-
.regex(/^\d{4}$/, {
38-
message: 'Invalid "year" parameter. Use YYYY format, e.g. 2024.',
39-
})
37+
.optional()
4038
.refine(
41-
(year) => {
42-
const yearNum = parseInt(year, 10);
39+
(val) => {
40+
if (!val) return true;
41+
const yearNum = parseInt(val, 10);
4342
const currentYear = new Date().getFullYear();
44-
45-
return yearNum >= 2005 && yearNum <= currentYear;
43+
return /^\d{4}$/.test(val) && yearNum >= 2008 && yearNum <= currentYear;
4644
},
4745
{
48-
message: 'Invalid "year" parameter. Use YYYY format, e.g. 2024.',
46+
message: 'GitHub was founded in 2008. Please provide a year of 2008 or later.',
4947
}
50-
)
51-
.optional(),
48+
),
5249
refresh: z
5350
.string()
5451
.optional()

0 commit comments

Comments
 (0)