File tree Expand file tree Collapse file tree 2 files changed +20
-1
lines changed
Expand file tree Collapse file tree 2 files changed +20
-1
lines changed Original file line number Diff line number Diff line change @@ -26,7 +26,16 @@ const server = fastify({logger: true});
2626/* Adding an authentication hook to the server. A hook is a function that is called when a request is made to
2727the server. */
2828server . addHook ( 'onRequest' , ( request , reply , done ) => {
29- if ( ! isAuthenticated ( request ) ) {
29+ const routeExists = server . hasRoute ( {
30+ url : request . raw . url ,
31+ method : request . raw . method
32+ // constraints: { version: '1.0.0' } specify this if you are doing something custom
33+ } ) ;
34+
35+ if ( ! routeExists ) {
36+ reply . code ( HTTP_STATUS_CODES . NOT_FOUND ) ;
37+ done ( new Error ( 'Not Found' ) ) ;
38+ } else if ( ! isAuthenticated ( request ) ) {
3039 reply . code ( HTTP_STATUS_CODES . UNAUTHORIZED ) ;
3140 done ( new Error ( 'Wrong key' ) ) ;
3241 } else {
Original file line number Diff line number Diff line change @@ -37,4 +37,14 @@ describe('Integration Tests for hello api', function () {
3737 "message" : "Wrong key" ,
3838 "statusCode" : 401 } ) ;
3939 } ) ;
40+
41+ it ( 'should reply 404 if route doesnt exist' , async function ( ) {
42+ let output = await fetch ( "http://localhost:5000/routeNotExist?name=world" , { method : 'GET' } ) ;
43+ output = await output . json ( ) ;
44+ expect ( output ) . eql ( {
45+ "statusCode" : 404 ,
46+ "error" : "Not Found" ,
47+ "message" : "Not Found"
48+ } ) ;
49+ } ) ;
4050} ) ;
You can’t perform that action at this time.
0 commit comments