Skip to content

Commit d9671a4

Browse files
committed
Implement POST API sample
1 parent de3c0da commit d9671a4

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

src/apis/index.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
1-
import { FastifyInstance } from 'fastify';
1+
import { FastifyInstance, RequestGenericInterface } from 'fastify';
2+
3+
interface PostReqSchema extends RequestGenericInterface {
4+
Body: { action: 'ping' }
5+
}
6+
7+
// Request schema validation & response serialisation for POST API
8+
const postOpts = {
9+
schema: {
10+
body: {
11+
type: 'object',
12+
required: ['action'],
13+
properties: {
14+
action: { type: 'string', enum: ['ping'] },
15+
},
16+
},
17+
},
18+
response: {
19+
200: {
20+
value: { type: 'string' },
21+
},
22+
},
23+
};
224

325
export default async (fastify: FastifyInstance): Promise<void> => {
426
fastify.get('/', async (_req, _reply) => 'hello world');
27+
28+
fastify.post<PostReqSchema>('/', postOpts, async (req, reply) => {
29+
await reply.code(200).send('pong');
30+
});
531
};

tests/apis/index.test.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,26 @@ beforeAll(async () => {
77
server = await createServer();
88
});
99

10-
test('root api', async () => {
11-
const res = await server.inject().get('/');
10+
describe('APIs - /', () => {
11+
test('GET /', async () => {
12+
const res = await server.inject().get('/');
1213

13-
expect(res.statusCode).toBe(200);
14-
expect(res.body).toMatch('hello world');
14+
expect(res.statusCode).toBe(200);
15+
expect(res.body).toMatch('hello world');
16+
});
17+
18+
test('POST /', async () => {
19+
const res = await server.inject().post('/').body({ action: 'ping' });
20+
21+
expect(res.statusCode).toBe(200);
22+
expect(res.body).toMatch('pong');
23+
});
24+
25+
test('Invalid POST /', async () => {
26+
const res = await server.inject().post('/').body({ action: '' });
27+
28+
expect(res.statusCode).toBe(400);
29+
});
1530
});
1631

1732
afterAll(async () => {

0 commit comments

Comments
 (0)