Skip to content

Commit 100eab4

Browse files
committed
Add Zod schema for stats
1 parent d8c692d commit 100eab4

3 files changed

Lines changed: 14 additions & 5 deletions

File tree

src/routes/stats.schema.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import * as z from 'zod';
2+
3+
export const statsResponseSchema = z.object({
4+
libraries: z.number(),
5+
}).partial();
6+
7+
export type StatsResponse = z.infer<typeof statsResponseSchema>;

src/routes/stats.spec.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, it, expect } from 'vitest';
22

3+
import type { StatsResponse } from './stats.schema.ts';
34
import testCors from '../utils/spec/cors.ts';
45
import testHuman from '../utils/spec/human.ts';
56
import { beforeRequest, request } from '../utils/spec/request.ts';
@@ -20,22 +21,22 @@ describe('/stats', () => {
2021
});
2122
it('returns a JSON body that is a stats object', async () => {
2223
expect(response.headers.get('Content-Type')).to.match(/application\/json/);
23-
expect(await response.json()).to.be.an('object');
24+
expect(await response.json<StatsResponse>()).to.be.an('object');
2425
});
2526
describe('cdnjs stats object', () => {
2627
it('is an object with the \'libraries\' property', async () => {
27-
expect(await response.json()).to.have.property('libraries').that.is.an('number');
28+
expect(await response.json<StatsResponse>()).to.have.property('libraries').that.is.an('number');
2829
});
2930
it('has no other properties', async () => {
30-
expect(Object.keys(await response.json())).to.have.lengthOf(1);
31+
expect(Object.keys(await response.json<StatsResponse>())).to.have.lengthOf(1);
3132
});
3233
});
3334

3435
// Test with a trailing slash
3536
it('responds to requests with a trailing slash', async () => {
3637
const res = await request(path + '/');
3738
expect(res.status).to.eq(200);
38-
expect(await res.json()).to.deep.equal(await response.json());
39+
expect(await res.json<StatsResponse>()).to.deep.equal(await response.json<StatsResponse>());
3940
});
4041
});
4142

src/routes/stats.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { Context, Hono } from 'hono';
22

3+
import type { StatsResponse } from './stats.schema.ts';
34
import cache from '../utils/cache.ts';
45
import filter from '../utils/filter.ts';
56
import { libraries } from '../utils/kvMetadata.ts';
@@ -27,7 +28,7 @@ const handleGetStats = async (ctx: Context) => {
2728
cache(ctx, 6 * 60 * 60);
2829

2930
// Send the response
30-
return respond(ctx, response);
31+
return respond(ctx, response satisfies StatsResponse);
3132
};
3233

3334
/**

0 commit comments

Comments
 (0)