File tree Expand file tree Collapse file tree 2 files changed +46
-5
lines changed
Expand file tree Collapse file tree 2 files changed +46
-5
lines changed Original file line number Diff line number Diff line change 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
325export 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} ;
Original file line number Diff line number Diff 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
1732afterAll ( async ( ) => {
You can’t perform that action at this time.
0 commit comments