Skip to content

Commit de3c0da

Browse files
committed
Refactor API /users
- Included examples on usage of query & params.
1 parent e0f4b6d commit de3c0da

File tree

2 files changed

+65
-10
lines changed

2 files changed

+65
-10
lines changed

src/apis/users/index.ts

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,46 @@
1-
import { FastifyInstance } from 'fastify';
1+
import { FastifyInstance, RequestGenericInterface } from 'fastify';
2+
3+
interface ReqSchema extends RequestGenericInterface {
4+
Querystring: {
5+
id?: number
6+
}
7+
}
8+
9+
// Request schema validation & response serialisation
10+
const opts = {
11+
schema: {
12+
querystring: {
13+
type: 'object',
14+
properties: {
15+
id: {
16+
type: 'number',
17+
nullable: true,
18+
},
19+
},
20+
},
21+
},
22+
response: {
23+
200: {
24+
type: 'object',
25+
properties: {
26+
user_id: { type: 'number' },
27+
validated: { type: 'boolean' },
28+
},
29+
},
30+
},
31+
};
232

333
export default async (fastify: FastifyInstance): Promise<void> => {
4-
fastify.get('/', async (_req, _reply) => 'pong');
34+
fastify.get<ReqSchema>('/', opts, async (req, reply) => {
35+
const { id } = req.query;
36+
37+
if (id == null) {
38+
await reply.redirect('/');
39+
} else {
40+
await reply.code(200).send({
41+
user_id: id,
42+
validated: id < 10,
43+
});
44+
}
45+
});
546
};

tests/apis/users.test.ts

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,32 @@ beforeAll(async () => {
77
server = await createServer();
88
});
99

10-
test('users', async () => {
11-
const res = await server.inject().get('/users');
10+
describe('APIs - /users', () => {
11+
it('should redirect to index', async () => {
12+
const res = await server.inject().get('/users');
13+
expect(res.statusCode).toBe(302);
14+
});
1215

13-
expect(res.statusCode).toBe(200);
14-
expect(res.body).toMatch('pong');
16+
it('should return true on user id validation', async () => {
17+
const res = await server.inject().get('/users').query({ id: 1 });
18+
expect(res.statusCode).toBe(200);
19+
expect(res.json()).toEqual({ user_id: 1, validated: true });
20+
});
21+
22+
it('should return false on user id validation', async () => {
23+
const res = await server.inject().get('/users').query({ id: 10 });
24+
expect(res.statusCode).toBe(200);
25+
expect(res.json()).toEqual({ user_id: 10, validated: false });
26+
});
1527
});
1628

17-
test('user by id', async () => {
18-
const res = await server.inject().get('/users/1');
29+
describe('API - /users/:id', () => {
30+
it('should return user id passed in', async () => {
31+
const res = await server.inject().get('/users/1');
1932

20-
expect(res.statusCode).toBe(200);
21-
expect(res.json()).toEqual({ user: 1 });
33+
expect(res.statusCode).toBe(200);
34+
expect(res.json()).toEqual({ user: 1 });
35+
});
2236
});
2337

2438
afterAll(async () => {

0 commit comments

Comments
 (0)